use tauri::{command, State};
use crate::app_state::AppState;
use crate::data::models::material_segment_view::{MaterialSegmentView, MaterialSegmentQuery};
use crate::business::services::material_segment_view_service::MaterialSegmentViewService;
use std::sync::Arc;

/// 获取项目的MaterialSegment聚合视图命令
/// 遵循 Tauri 开发规范的命令设计模式
#[command]
pub async fn get_project_segment_view(
    project_id: String,
    state: State<'_, AppState>,
) -> Result<MaterialSegmentView, String> {
    // 获取数据库实例
    let database = state.get_database();

    // 创建仓库实例
    let material_repository = Arc::new(
        crate::data::repositories::material_repository::MaterialRepository::new(
            database.clone()
        ).map_err(|e| format!("创建素材仓库失败: {}", e))?
    );

    let video_classification_repository = Arc::new(
        crate::data::repositories::video_classification_repository::VideoClassificationRepository::new(
            database.clone()
        )
    );

    let model_repository = Arc::new(
        crate::data::repositories::model_repository::ModelRepository::new(
            database.clone()
        )
    );

    // 创建服务实例
    let service = MaterialSegmentViewService::new(
        material_repository,
        video_classification_repository,
        model_repository,
    );

    // 调用服务方法
    service.get_project_segment_view(&project_id)
        .await
        .map_err(|e| format!("获取MaterialSegment聚合视图失败: {}", e))
}

/// 根据查询条件获取项目的MaterialSegment聚合视图命令
#[command]
pub async fn get_project_segment_view_with_query(
    query: MaterialSegmentQuery,
    state: State<'_, AppState>,
) -> Result<MaterialSegmentView, String> {
    // 获取数据库实例
    let database = state.get_database();

    // 创建仓库实例
    let material_repository = Arc::new(
        crate::data::repositories::material_repository::MaterialRepository::new(
            database.clone()
        ).map_err(|e| format!("创建素材仓库失败: {}", e))?
    );

    let video_classification_repository = Arc::new(
        crate::data::repositories::video_classification_repository::VideoClassificationRepository::new(
            database.clone()
        )
    );

    let model_repository = Arc::new(
        crate::data::repositories::model_repository::ModelRepository::new(
            database.clone()
        )
    );

    // 创建服务实例
    let service = MaterialSegmentViewService::new(
        material_repository,
        video_classification_repository,
        model_repository,
    );

    // 调用服务方法
    service.get_project_segment_view_with_query(&query)
        .await
        .map_err(|e| format!("获取MaterialSegment聚合视图失败: {}", e))
}
