use tauri::State;
use anyhow::Result;
use crate::app_state::AppState;
use crate::data::models::custom_tag::*;
use crate::data::repositories::custom_tag_repository::CustomTagRepository;

/// 获取所有标签分类
/// 遵循 Tauri 开发规范的命令设计原则
#[tauri::command]
pub async fn get_custom_tag_categories(
    state: State<'_, AppState>,
    active_only: Option<bool>,
) -> Result<Vec<CustomTagCategory>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .get_all_categories(active_only.unwrap_or(true))
        .await
        .map_err(|e| {
            eprintln!("Failed to get custom tag categories: {}", e);
            format!("获取标签分类失败: {}", e)
        })
}

/// 创建标签分类
#[tauri::command]
pub async fn create_custom_tag_category(
    state: State<'_, AppState>,
    request: CreateCustomTagCategoryRequest,
) -> Result<CustomTagCategory, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .create_category(request)
        .await
        .map_err(|e| {
            eprintln!("Failed to create custom tag category: {}", e);
            format!("创建标签分类失败: {}", e)
        })
}

/// 更新标签分类
#[tauri::command]
pub async fn update_custom_tag_category(
    state: State<'_, AppState>,
    id: String,
    request: UpdateCustomTagCategoryRequest,
) -> Result<Option<CustomTagCategory>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .update_category(&id, request)
        .await
        .map_err(|e| {
            eprintln!("Failed to update custom tag category: {}", e);
            format!("更新标签分类失败: {}", e)
        })
}

/// 删除标签分类
#[tauri::command]
pub async fn delete_custom_tag_category(
    state: State<'_, AppState>,
    id: String,
) -> Result<bool, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .delete_category(&id)
        .await
        .map_err(|e| {
            eprintln!("Failed to delete custom tag category: {}", e);
            format!("删除标签分类失败: {}", e)
        })
}

/// 获取标签列表
#[tauri::command]
pub async fn get_custom_tags(
    state: State<'_, AppState>,
    filter: Option<TagFilter>,
) -> Result<Vec<CustomTagWithCategory>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .get_tags(filter.unwrap_or_default())
        .await
        .map_err(|e| {
            eprintln!("Failed to get custom tags: {}", e);
            format!("获取标签列表失败: {}", e)
        })
}

/// 创建标签
#[tauri::command]
pub async fn create_custom_tag(
    state: State<'_, AppState>,
    request: CreateCustomTagRequest,
) -> Result<CustomTag, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .create_tag(request)
        .await
        .map_err(|e| {
            eprintln!("Failed to create custom tag: {}", e);
            format!("创建标签失败: {}", e)
        })
}

/// 更新标签
#[tauri::command]
pub async fn update_custom_tag(
    state: State<'_, AppState>,
    id: String,
    request: UpdateCustomTagRequest,
) -> Result<Option<CustomTag>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .update_tag(&id, request)
        .await
        .map_err(|e| {
            eprintln!("Failed to update custom tag: {}", e);
            format!("更新标签失败: {}", e)
        })
}

/// 删除标签
#[tauri::command]
pub async fn delete_custom_tag(
    state: State<'_, AppState>,
    id: String,
) -> Result<bool, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .delete_tag(&id)
        .await
        .map_err(|e| {
            eprintln!("Failed to delete custom tag: {}", e);
            format!("删除标签失败: {}", e)
        })
}

/// 为实体添加标签
#[tauri::command]
pub async fn add_entity_tag(
    state: State<'_, AppState>,
    tag_id: String,
    entity_type: String,
    entity_id: String,
) -> Result<TagAssociation, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .create_tag_association(&tag_id, &entity_type, &entity_id)
        .await
        .map_err(|e| {
            eprintln!("Failed to add entity tag: {}", e);
            format!("添加实体标签失败: {}", e)
        })
}

/// 移除实体标签
#[tauri::command]
pub async fn remove_entity_tag(
    state: State<'_, AppState>,
    tag_id: String,
    entity_type: String,
    entity_id: String,
) -> Result<bool, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .delete_tag_association(&tag_id, &entity_type, &entity_id)
        .await
        .map_err(|e| {
            eprintln!("Failed to remove entity tag: {}", e);
            format!("移除实体标签失败: {}", e)
        })
}

/// 获取实体的标签
#[tauri::command]
pub async fn get_entity_tags(
    state: State<'_, AppState>,
    entity_type: String,
    entity_id: String,
) -> Result<Vec<CustomTagWithCategory>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .get_entity_tags(&entity_type, &entity_id)
        .await
        .map_err(|e| {
            eprintln!("Failed to get entity tags: {}", e);
            format!("获取实体标签失败: {}", e)
        })
}

/// 获取标签统计信息
#[tauri::command]
pub async fn get_tag_statistics(
    state: State<'_, AppState>,
) -> Result<TagStatistics, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    repository
        .get_tag_statistics()
        .await
        .map_err(|e| {
            eprintln!("Failed to get tag statistics: {}", e);
            format!("获取标签统计失败: {}", e)
        })
}

/// 批量为实体添加标签
#[tauri::command]
pub async fn batch_add_entity_tags(
    state: State<'_, AppState>,
    tag_ids: Vec<String>,
    entity_type: String,
    entity_id: String,
) -> Result<Vec<TagAssociation>, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    let mut associations = Vec::new();
    for tag_id in tag_ids {
        match repository.create_tag_association(&tag_id, &entity_type, &entity_id).await {
            Ok(association) => associations.push(association),
            Err(e) => {
                eprintln!("Failed to add tag {} to entity {}: {}", tag_id, entity_id, e);
                // 继续处理其他标签，不中断整个操作
            }
        }
    }

    Ok(associations)
}

/// 批量移除实体标签
#[tauri::command]
pub async fn batch_remove_entity_tags(
    state: State<'_, AppState>,
    tag_ids: Vec<String>,
    entity_type: String,
    entity_id: String,
) -> Result<i32, String> {
    let database = {
        let database_guard = state.database.lock().unwrap();
        database_guard.as_ref().ok_or("Database not initialized")?.clone()
    };
    let repository = CustomTagRepository::new(database);

    let mut removed_count = 0;
    for tag_id in tag_ids {
        match repository.delete_tag_association(&tag_id, &entity_type, &entity_id).await {
            Ok(true) => removed_count += 1,
            Ok(false) => {
                // 标签关联不存在，继续处理
            }
            Err(e) => {
                eprintln!("Failed to remove tag {} from entity {}: {}", tag_id, entity_id, e);
                // 继续处理其他标签，不中断整个操作
            }
        }
    }

    Ok(removed_count)
}
