use serde::Deserialize;
use tauri::State;

use crate::db::connection::DbManager;
use crate::domains::series_spell::service;
use crate::error::AppError;
use crate::shared::session::SessionState;
use crate::shared::types::Lang;

fn get_session(session: &State<SessionState>) -> Result<(String, Lang), AppError> {
    let session_guard = session.lock().map_err(|e| AppError::Internal(format!("Session lock failed: {}", e)))?;
    let user_id = session_guard.get_user_id().map_err(|e| AppError::Auth(e))?.to_string();
    let lang = session_guard.lang;
    Ok((user_id, lang))
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSeriesSpellListData { pub series_id: String }

#[tauri::command]
pub fn get_series_spell_list(data: GetSeriesSpellListData, db: State<DbManager>, session: State<SessionState>) -> Result<service::SeriesSpellListResponse, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::get_spell_list(conn, &user_id, &data.series_id, lang)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetSeriesSpellDetailData { pub spell_id: String }

#[tauri::command]
pub fn get_series_spell_detail(data: GetSeriesSpellDetailData, db: State<DbManager>, session: State<SessionState>) -> Result<service::SeriesSpellDetailProps, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::get_spell_detail(conn, &user_id, &data.spell_id, lang)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddSeriesSpellData {
    pub series_id: String,
    pub name: String,
    pub description: Option<String>,
    pub appearance: Option<String>,
    pub tags: Option<Vec<String>>,
    pub power_level: Option<String>,
    pub components: Option<String>,
    pub limitations: Option<String>,
    pub notes: Option<String>,
}

#[tauri::command]
pub fn add_series_spell(data: AddSeriesSpellData, db: State<DbManager>, session: State<SessionState>) -> Result<String, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::add_spell(
        conn, &user_id, &data.series_id, &data.name, lang,
        data.description.as_deref(), data.appearance.as_deref(), data.tags,
        data.power_level.as_deref(), data.components.as_deref(),
        data.limitations.as_deref(), data.notes.as_deref(),
    )
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateSeriesSpellData {
    pub spell_id: String,
    pub name: String,
    pub description: Option<String>,
    pub appearance: Option<String>,
    pub tags: Option<Vec<String>>,
    pub power_level: Option<String>,
    pub components: Option<String>,
    pub limitations: Option<String>,
    pub notes: Option<String>,
}

#[tauri::command]
pub fn update_series_spell(data: UpdateSeriesSpellData, db: State<DbManager>, session: State<SessionState>) -> Result<bool, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::update_spell(
        conn, &user_id, &data.spell_id, &data.name, lang,
        data.description.as_deref(), data.appearance.as_deref(), data.tags,
        data.power_level.as_deref(), data.components.as_deref(),
        data.limitations.as_deref(), data.notes.as_deref(),
    )
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteSeriesSpellData { pub spell_id: String, pub deleted_at: i64 }

#[tauri::command]
pub fn delete_series_spell(data: DeleteSeriesSpellData, db: State<DbManager>, session: State<SessionState>) -> Result<bool, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::delete_spell(conn, &user_id, &data.spell_id, data.deleted_at, lang)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddSeriesSpellTagData { pub series_id: String, pub name: String, pub color: Option<String> }

#[tauri::command]
pub fn add_series_spell_tag(data: AddSeriesSpellTagData, db: State<DbManager>, session: State<SessionState>) -> Result<String, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::add_tag(conn, &user_id, &data.series_id, &data.name, lang, data.color.as_deref())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateSeriesSpellTagData { pub tag_id: String, pub name: String, pub color: Option<String> }

#[tauri::command]
pub fn update_series_spell_tag(data: UpdateSeriesSpellTagData, db: State<DbManager>, session: State<SessionState>) -> Result<bool, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::update_tag(conn, &user_id, &data.tag_id, &data.name, lang, data.color.as_deref())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteSeriesSpellTagData { pub tag_id: String, pub deleted_at: i64 }

#[tauri::command]
pub fn delete_series_spell_tag(data: DeleteSeriesSpellTagData, db: State<DbManager>, session: State<SessionState>) -> Result<bool, AppError> {
    let (user_id, lang) = get_session(&session)?;
    let db_manager = db.lock().map_err(|e| AppError::Internal(format!("DB lock failed: {}", e)))?;
    let conn = db_manager.get_connection(&user_id)?;
    service::delete_tag(conn, &user_id, &data.tag_id, data.deleted_at, lang)
}
