use crate::error::AppError;
use crate::models::module::ProjectModule;
use crate::AppState;
use tauri::State;

#[tauri::command]
pub fn list_project_modules(
    state: State<'_, AppState>,
    project_id: String,
) -> Result<Vec<ProjectModule>, AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    let modules = ProjectModule::list_by_project(&db, &project_id)?;
    Ok(modules)
}

#[tauri::command]
pub fn set_project_module_enabled(
    state: State<'_, AppState>,
    project_id: String,
    module_key: String,
    enabled: bool,
) -> Result<(), AppError> {
    let db = state
        .db
        .lock()
        .map_err(|e| AppError::from(format!("Database lock failed: {}", e)))?;

    ProjectModule::ensure_defaults_for_project(&db, &project_id)?;
    ProjectModule::set_enabled(&db, &project_id, &module_key, enabled)?;
    Ok(())
}
