use tauri::{command, State};
use crate::app_state::AppState;
use crate::business::services::project_service::ProjectService;
use crate::data::models::project::{Project, CreateProjectRequest, UpdateProjectRequest};

/// 创建项目命令
/// 遵循 Tauri 开发规范的命令设计模式
#[command]
pub async fn create_project(
    state: State<'_, AppState>,
    request: CreateProjectRequest,
) -> Result<Project, String> {
    let repository_guard = state.get_project_repository()
        .map_err(|e| format!("获取项目仓库失败: {}", e))?;
    
    let repository = repository_guard.as_ref()
        .ok_or("项目仓库未初始化")?;

    ProjectService::create_project(repository, request)
        .map_err(|e| e.to_string())
}

/// 获取所有项目命令
#[command]
pub async fn get_all_projects(
    state: State<'_, AppState>,
) -> Result<Vec<Project>, String> {
    let repository_guard = state.get_project_repository()
        .map_err(|e| format!("获取项目仓库失败: {}", e))?;
    
    let repository = repository_guard.as_ref()
        .ok_or("项目仓库未初始化")?;

    ProjectService::get_all_projects(repository)
        .map_err(|e| e.to_string())
}

/// 根据ID获取项目命令
#[command]
pub async fn get_project_by_id(
    state: State<'_, AppState>,
    id: String,
) -> Result<Option<Project>, String> {
    let repository_guard = state.get_project_repository()
        .map_err(|e| format!("获取项目仓库失败: {}", e))?;
    
    let repository = repository_guard.as_ref()
        .ok_or("项目仓库未初始化")?;

    ProjectService::get_project_by_id(repository, &id)
        .map_err(|e| e.to_string())
}

/// 更新项目命令
#[command]
pub async fn update_project(
    state: State<'_, AppState>,
    id: String,
    request: UpdateProjectRequest,
) -> Result<Project, String> {
    let repository_guard = state.get_project_repository()
        .map_err(|e| format!("获取项目仓库失败: {}", e))?;
    
    let repository = repository_guard.as_ref()
        .ok_or("项目仓库未初始化")?;

    ProjectService::update_project(repository, &id, request)
        .map_err(|e| e.to_string())
}

/// 删除项目命令
#[command]
pub async fn delete_project(
    state: State<'_, AppState>,
    id: String,
) -> Result<(), String> {
    let repository_guard = state.get_project_repository()
        .map_err(|e| format!("获取项目仓库失败: {}", e))?;
    
    let repository = repository_guard.as_ref()
        .ok_or("项目仓库未初始化")?;

    ProjectService::delete_project(repository, &id)
        .map_err(|e| e.to_string())
}

/// 验证项目路径命令
#[command]
pub async fn validate_project_path(path: String) -> Result<bool, String> {
    ProjectService::validate_project_path(&path)
        .map_err(|e| e.to_string())
}

/// 获取默认项目名称命令
#[command]
pub async fn get_default_project_name(path: String) -> Result<String, String> {
    ProjectService::get_default_project_name(&path)
        .map_err(|e| e.to_string())
}
