//! Per-series preferred audio track commands.
//!
//! TRACES: UR-021 | DR-024

use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tauri::State;

use super::DatabaseWrapper;
use crate::storage::db_service::{DatabaseService, Query, QueryParam};

/// Audio track preference for a series
#[derive(specta::Type, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SeriesAudioPreference {
    pub series_id: String,
    pub audio_track_display_title: Option<String>,
    pub audio_track_language: Option<String>,
    pub audio_track_index: Option<i32>,
}

/// Save user's preferred audio track for a series
#[tauri::command]
#[specta::specta]
pub async fn storage_save_series_audio_preference(
    db: State<'_, DatabaseWrapper>,
    user_id: String,
    series_id: String,
    server_id: String,
    audio_track_display_title: Option<String>,
    audio_track_language: Option<String>,
    audio_track_index: Option<i32>,
) -> Result<(), String> {
    let db_service = {
        let database = db.0.lock().map_err(|e| e.to_string())?;
        Arc::new(database.service())
    };

    let query = Query::with_params(
        "INSERT INTO series_audio_preferences
            (user_id, series_id, server_id, audio_track_display_title, audio_track_language, audio_track_index, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, datetime('now'))
         ON CONFLICT (user_id, series_id, server_id) DO UPDATE SET
            audio_track_display_title = excluded.audio_track_display_title,
            audio_track_language = excluded.audio_track_language,
            audio_track_index = excluded.audio_track_index,
            updated_at = datetime('now')",
        vec![
            QueryParam::String(user_id),
            QueryParam::String(series_id),
            QueryParam::String(server_id),
            audio_track_display_title.map(QueryParam::String).unwrap_or(QueryParam::Null),
            audio_track_language.map(QueryParam::String).unwrap_or(QueryParam::Null),
            audio_track_index.map(|i| QueryParam::Int64(i as i64)).unwrap_or(QueryParam::Null),
        ],
    );

    db_service.execute(query).await.map_err(|e| e.to_string())?;
    Ok(())
}

/// Get user's preferred audio track for a series
#[tauri::command]
#[specta::specta]
pub async fn storage_get_series_audio_preference(
    db: State<'_, DatabaseWrapper>,
    user_id: String,
    series_id: String,
) -> Result<Option<SeriesAudioPreference>, String> {
    let db_service = {
        let database = db.0.lock().map_err(|e| e.to_string())?;
        Arc::new(database.service())
    };

    let query = Query::with_params(
        "SELECT series_id, audio_track_display_title, audio_track_language, audio_track_index
         FROM series_audio_preferences
         WHERE user_id = ? AND series_id = ?",
        vec![QueryParam::String(user_id), QueryParam::String(series_id)],
    );

    let preference = db_service
        .query_optional(query, |row| {
            Ok(SeriesAudioPreference {
                series_id: row.get(0)?,
                audio_track_display_title: row.get(1)?,
                audio_track_language: row.get(2)?,
                audio_track_index: row.get(3)?,
            })
        })
        .await
        .map_err(|e| e.to_string())?;

    Ok(preference)
}
