/**
 * 导出记录相关的 Tauri 命令
 * 遵循 Tauri 开发规范的 API 设计原则
 */

use tauri::{command, State};
use std::sync::Arc;

use crate::business::services::export_record_service::ExportRecordService;
use crate::data::models::export_record::{
    ExportRecord, ExportRecordQueryOptions, ExportRecordStatistics,
};
use crate::data::repositories::export_record_repository::ExportRecordRepository;
use crate::data::repositories::template_matching_result_repository::TemplateMatchingResultRepository;
use crate::infrastructure::database::Database;

/// 获取导出记录详情
#[command]
pub async fn get_export_record(
    record_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<Option<ExportRecord>, String> {
    println!("📋 获取导出记录详情: {}", record_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.get_export_record(&record_id).await {
        Ok(record) => {
            println!("✅ 获取导出记录成功");
            Ok(record)
        }
        Err(e) => {
            println!("❌ 获取导出记录失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 查询导出记录列表
#[command]
pub async fn list_export_records(
    options: ExportRecordQueryOptions,
    database: State<'_, Arc<Database>>,
) -> Result<Vec<ExportRecord>, String> {
    println!("📋 查询导出记录列表");

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.list_export_records(options).await {
        Ok(records) => {
            println!("✅ 查询导出记录列表成功，共 {} 条记录", records.len());
            Ok(records)
        }
        Err(e) => {
            println!("❌ 查询导出记录列表失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 获取项目的导出记录
#[command]
pub async fn get_project_export_records(
    project_id: String,
    limit: Option<u32>,
    offset: Option<u32>,
    database: State<'_, Arc<Database>>,
) -> Result<Vec<ExportRecord>, String> {
    println!("📋 获取项目导出记录: {}", project_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.get_project_exports(&project_id, limit, offset).await {
        Ok(records) => {
            println!("✅ 获取项目导出记录成功，共 {} 条记录", records.len());
            Ok(records)
        }
        Err(e) => {
            println!("❌ 获取项目导出记录失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 获取匹配结果的导出记录
#[command]
pub async fn get_matching_result_export_records(
    matching_result_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<Vec<ExportRecord>, String> {
    println!("📋 获取匹配结果导出记录: {}", matching_result_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.get_matching_result_exports(&matching_result_id).await {
        Ok(records) => {
            println!("✅ 获取匹配结果导出记录成功，共 {} 条记录", records.len());
            Ok(records)
        }
        Err(e) => {
            println!("❌ 获取匹配结果导出记录失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 删除导出记录
#[command]
pub async fn delete_export_record(
    record_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<(), String> {
    println!("🗑️ 删除导出记录: {}", record_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.delete_export_record(&record_id).await {
        Ok(_) => {
            println!("✅ 删除导出记录成功");
            Ok(())
        }
        Err(e) => {
            println!("❌ 删除导出记录失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 获取项目导出统计信息
#[command]
pub async fn get_project_export_statistics(
    project_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<ExportRecordStatistics, String> {
    println!("📊 获取项目导出统计信息: {}", project_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.get_project_export_statistics(&project_id).await {
        Ok(statistics) => {
            println!("✅ 获取项目导出统计信息成功");
            Ok(statistics)
        }
        Err(e) => {
            println!("❌ 获取项目导出统计信息失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 获取全局导出统计信息
#[command]
pub async fn get_global_export_statistics(
    database: State<'_, Arc<Database>>,
) -> Result<ExportRecordStatistics, String> {
    println!("📊 获取全局导出统计信息");

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.get_global_export_statistics().await {
        Ok(statistics) => {
            println!("✅ 获取全局导出统计信息成功");
            Ok(statistics)
        }
        Err(e) => {
            println!("❌ 获取全局导出统计信息失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 验证导出文件是否存在
#[command]
pub async fn validate_export_file(
    record_id: String,
    database: State<'_, Arc<Database>>,
) -> Result<bool, String> {
    println!("🔍 验证导出文件: {}", record_id);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.validate_export_file(&record_id).await {
        Ok(exists) => {
            println!("✅ 验证导出文件完成: {}", if exists { "存在" } else { "不存在" });
            Ok(exists)
        }
        Err(e) => {
            println!("❌ 验证导出文件失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 清理过期的导出记录
#[command]
pub async fn cleanup_expired_export_records(
    days: u32,
    database: State<'_, Arc<Database>>,
) -> Result<u32, String> {
    println!("🧹 清理过期导出记录（超过 {} 天）", days);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.cleanup_expired_records(days).await {
        Ok(count) => {
            println!("✅ 清理过期导出记录完成，共清理 {} 条记录", count);
            Ok(count)
        }
        Err(e) => {
            println!("❌ 清理过期导出记录失败: {}", e);
            Err(e.to_string())
        }
    }
}

/// 重新导出
#[command]
pub async fn re_export_record(
    record_id: String,
    new_file_path: String,
    database: State<'_, Arc<Database>>,
) -> Result<ExportRecord, String> {
    println!("🔄 重新导出: {} -> {}", record_id, new_file_path);

    let export_record_repository = Arc::new(ExportRecordRepository::new(database.inner().clone()));
    let matching_result_repository = Arc::new(TemplateMatchingResultRepository::new(database.inner().clone()));
    let service = ExportRecordService::new(export_record_repository, matching_result_repository);

    match service.re_export(&record_id, new_file_path).await {
        Ok(new_record) => {
            println!("✅ 重新导出成功，新记录ID: {}", new_record.id);
            Ok(new_record)
        }
        Err(e) => {
            println!("❌ 重新导出失败: {}", e);
            Err(e.to_string())
        }
    }
}
