use rusqlite::{params, Connection};
use serde::{Deserialize, Serialize};

// ── 数据结构 ──────────────────────────────────────────────────────────────────

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ServiceConfig {
    pub id: String,
    pub server_id: String,
    pub name: String,
    pub category: Option<String>,
    pub scope: Option<String>,
    pub config_data: String,
    pub sort_order: Option<i32>,
    pub created_at: Option<String>,
    pub updated_at: Option<String>,
}

#[derive(Debug, Deserialize)]
pub struct SaveServiceConfigInput {
    pub name: String,
    pub category: Option<String>,
    pub scope: Option<String>,
    pub config_data: String,
    pub sort_order: Option<i32>,
}

// ── 业务函数 ──────────────────────────────────────────────────────────────────

pub fn list_service_configs(conn: &Connection, server_id: &str, scope: &str) -> Vec<ServiceConfig> {
    let mut stmt = match conn.prepare(
        "SELECT id, server_id, name, category, scope, config_data, sort_order, created_at, updated_at
         FROM server_service_configs
         WHERE server_id = ?1 AND (scope = ?2 OR scope IS NULL)
         ORDER BY sort_order ASC, created_at ASC",
    ) {
        Ok(s) => s,
        Err(_) => return vec![],
    };
    stmt.query_map(params![server_id, scope], |row| {
        Ok(ServiceConfig {
            id:          row.get(0)?,
            server_id:   row.get(1)?,
            name:        row.get(2)?,
            category:    row.get(3)?,
            scope:       row.get(4)?,
            config_data: row.get(5)?,
            sort_order:  row.get(6)?,
            created_at:  row.get(7)?,
            updated_at:  row.get(8)?,
        })
    })
    .map(|iter| iter.filter_map(|r| r.ok()).collect())
    .unwrap_or_default()
}

fn row_to_config(row: &rusqlite::Row<'_>) -> rusqlite::Result<ServiceConfig> {
    Ok(ServiceConfig {
        id:          row.get(0)?,
        server_id:   row.get(1)?,
        name:        row.get(2)?,
        category:    row.get(3)?,
        scope:       row.get(4)?,
        config_data: row.get(5)?,
        sort_order:  row.get(6)?,
        created_at:  row.get(7)?,
        updated_at:  row.get(8)?,
    })
}

pub fn get_service_config(conn: &Connection, id: &str) -> Option<ServiceConfig> {
    conn.query_row(
        "SELECT id, server_id, name, category, scope, config_data, sort_order, created_at, updated_at
         FROM server_service_configs WHERE id = ?1",
        params![id],
        row_to_config,
    )
    .ok()
}

pub fn create_service_config(
    conn: &Connection,
    server_id: &str,
    input: &SaveServiceConfigInput,
) -> Result<ServiceConfig, String> {
    let id = format!("svc-{}", uuid::Uuid::new_v4());
    let scope = input.scope.as_deref().unwrap_or("system");
    conn.execute(
        "INSERT INTO server_service_configs (id, server_id, name, category, scope, config_data, sort_order)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
        params![id, server_id, input.name, input.category, scope, input.config_data, input.sort_order.unwrap_or(0)],
    )
    .map_err(|e| e.to_string())?;
    get_service_config(conn, &id).ok_or_else(|| "创建后查询失败".into())
}

pub fn update_service_config(
    conn: &Connection,
    id: &str,
    input: &SaveServiceConfigInput,
) -> Result<ServiceConfig, String> {
    let rows = conn.execute(
        "UPDATE server_service_configs SET
            name = ?1, category = ?2, config_data = ?3, sort_order = ?4,
            updated_at = datetime('now')
         WHERE id = ?5",
        params![input.name, input.category, input.config_data, input.sort_order.unwrap_or(0), id],
    )
    .map_err(|e| e.to_string())?;
    if rows == 0 {
        return Err(format!("配置 {} 不存在", id));
    }
    get_service_config(conn, id).ok_or_else(|| "更新后查询失败".into())
}

pub fn delete_service_config_fn(conn: &Connection, id: &str) -> Result<(), String> {
    conn.execute("DELETE FROM server_service_configs WHERE id = ?1", params![id])
        .map_err(|e| e.to_string())?;
    Ok(())
}

pub fn delete_configs_by_server(conn: &Connection, server_id: &str) -> Result<(), String> {
    conn.execute("DELETE FROM server_service_configs WHERE server_id = ?1", params![server_id])
        .map_err(|e| e.to_string())?;
    Ok(())
}

// ── Tauri command 薄包装层 ────────────────────────────────────────────────────

#[tauri::command]
pub fn get_service_configs(server_id: String, scope: Option<String>) -> Result<Vec<ServiceConfig>, String> {
    let conn = crate::db::pool().get().map_err(|e| e.to_string())?;
    let s = scope.as_deref().unwrap_or("system");
    Ok(list_service_configs(&conn, &server_id, s))
}

#[tauri::command]
pub fn add_service_config(server_id: String, input: SaveServiceConfigInput) -> Result<ServiceConfig, String> {
    let conn = crate::db::pool().get().map_err(|e| e.to_string())?;
    create_service_config(&conn, &server_id, &input)
}

#[tauri::command]
pub fn edit_service_config(id: String, input: SaveServiceConfigInput) -> Result<ServiceConfig, String> {
    let conn = crate::db::pool().get().map_err(|e| e.to_string())?;
    update_service_config(&conn, &id, &input)
}

#[tauri::command]
pub fn delete_service_config(id: String) -> Result<(), String> {
    let conn = crate::db::pool().get().map_err(|e| e.to_string())?;
    delete_service_config_fn(&conn, &id)
}
