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

use crate::db::connection::DbManager;
use crate::domains::location::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 GetAllLocationsData {
    pub book_id: String,
}

#[tauri::command]
pub fn get_all_locations(data: GetAllLocationsData, db: State<DbManager>, session: State<SessionState>) -> Result<service::LocationListResponse, 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_all_locations(conn, &user_id, &data.book_id, lang)
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddLocationSectionData {
    pub location_name: String,
    pub book_id: String,
    pub id: Option<String>,
    pub series_location_id: Option<String>,
}

#[tauri::command]
pub fn add_location_section(data: AddLocationSectionData, 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_location_section(conn, &user_id, &data.location_name, &data.book_id, lang, data.id.as_deref(), data.series_location_id.as_deref())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddLocationElementData {
    pub location_id: String,
    pub element_name: String,
    pub id: Option<String>,
}

#[tauri::command]
pub fn add_location_element(data: AddLocationElementData, 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_location_element(conn, &user_id, &data.location_id, &data.element_name, lang, data.id.as_deref())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddLocationSubElementData {
    pub element_id: String,
    pub sub_element_name: String,
    pub id: Option<String>,
}

#[tauri::command]
pub fn add_location_sub_element(data: AddLocationSubElementData, 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_location_sub_element(conn, &user_id, &data.element_id, &data.sub_element_name, lang, data.id.as_deref())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateLocationsData {
    pub locations: Vec<service::LocationProps>,
}

#[tauri::command]
pub fn update_locations(data: UpdateLocationsData, db: State<DbManager>, session: State<SessionState>) -> Result<serde_json::Value, 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)?;
    let (success, message) = service::update_location_section(conn, &user_id, &data.locations, lang)?;
    Ok(serde_json::json!({"success": success, "message": message}))
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateLocationSectionWithSeriesLinkData {
    pub section_id: String,
    pub section_name: Option<String>,
    pub series_location_id: Option<String>,
}

#[tauri::command]
pub fn update_location_section_with_series_link(data: UpdateLocationSectionWithSeriesLinkData, 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_section_with_series_link(conn, &user_id, &data.section_id, data.section_name.as_deref(), data.series_location_id.as_deref(), lang)
}

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

#[tauri::command]
pub fn delete_location_section(data: DeleteLocationSectionData, 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_location_section(conn, &user_id, &data.book_id, &data.location_id, data.deleted_at, lang)
}

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

#[tauri::command]
pub fn delete_location_element(data: DeleteLocationElementData, 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_location_element(conn, &user_id, &data.book_id, &data.element_id, data.deleted_at, lang)
}

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

#[tauri::command]
pub fn delete_location_sub_element(data: DeleteLocationSubElementData, 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_location_sub_element(conn, &user_id, &data.book_id, &data.sub_element_id, data.deleted_at, lang)
}
