use crate::data::models::ai_classification::{
    AiClassification, CreateAiClassificationRequest, UpdateAiClassificationRequest, AiClassificationQuery
};
use crate::infrastructure::database::Database;
use anyhow::Result;
use chrono::{DateTime, Utc};
use rusqlite::{params, Row, OptionalExtension};
use std::sync::Arc;
use uuid::Uuid;

/// AI分类仓储层
/// 遵循 Tauri 开发规范的数据访问层设计原则
pub struct AiClassificationRepository {
    database: Arc<Database>,
}

impl AiClassificationRepository {
    /// 创建新的AI分类仓储实例
    pub fn new(database: Arc<Database>) -> Self {
        Self { database }
    }

    /// 创建AI分类
    pub async fn create(&self, request: CreateAiClassificationRequest) -> Result<AiClassification> {
        let id = Uuid::new_v4().to_string();
        let now = Utc::now();
        let sort_order = request.sort_order.unwrap_or(0);

        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        conn.execute(
            "INSERT INTO ai_classifications (
                id, name, prompt_text, description, is_active, sort_order, created_at, updated_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            params![
                id,
                request.name,
                request.prompt_text,
                request.description,
                1, // SQLite中布尔值存储为INTEGER
                sort_order,
                now.to_rfc3339(),
                now.to_rfc3339()
            ],
        )?;

        Ok(AiClassification {
            id,
            name: request.name,
            prompt_text: request.prompt_text,
            description: request.description,
            is_active: true,
            sort_order,
            created_at: now,
            updated_at: now,
        })
    }

    /// 根据ID获取AI分类
    pub async fn get_by_id(&self, id: &str) -> Result<Option<AiClassification>> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare(
            "SELECT id, name, prompt_text, description, is_active, sort_order, created_at, updated_at
             FROM ai_classifications WHERE id = ?1"
        )?;

        let classification = stmt.query_row(params![id], |row| {
            self.row_to_classification(row)
        }).optional()?;

        Ok(classification)
    }

    /// 获取所有AI分类
    pub async fn get_all(&self, query: Option<AiClassificationQuery>) -> Result<Vec<AiClassification>> {
        let query = query.unwrap_or_default();
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let mut sql = "SELECT id, name, prompt_text, description, is_active, sort_order, created_at, updated_at
                       FROM ai_classifications".to_string();

        // 添加查询条件
        if let Some(active_only) = query.active_only {
            if active_only {
                sql.push_str(" WHERE is_active = 1");
            }
        }

        // 添加排序
        let sort_by = query.sort_by.unwrap_or_else(|| "sort_order".to_string());
        let sort_order = query.sort_order.unwrap_or_else(|| "ASC".to_string());
        sql.push_str(&format!(" ORDER BY {} {}", sort_by, sort_order));

        // 添加分页
        if let Some(limit) = query.limit {
            sql.push_str(&format!(" LIMIT {}", limit));
            if let Some(offset) = query.offset {
                sql.push_str(&format!(" OFFSET {}", offset));
            }
        }

        let mut stmt = conn.prepare(&sql)?;
        let classification_iter = stmt.query_map([], |row| {
            self.row_to_classification(row)
        })?;

        let mut classifications = Vec::new();
        for classification in classification_iter {
            classifications.push(classification?);
        }

        Ok(classifications)
    }

    /// 更新AI分类
    pub async fn update(&self, id: &str, request: UpdateAiClassificationRequest) -> Result<Option<AiClassification>> {
        // 首先检查分类是否存在
        let exists = {
            let conn = self.database.get_connection();
            let conn = conn.lock().unwrap();
            conn.query_row(
                "SELECT 1 FROM ai_classifications WHERE id = ?1",
                params![id],
                |_| Ok(true)
            ).unwrap_or(false)
        };

        if !exists {
            return Ok(None);
        }

        let mut updates = Vec::new();
        let mut param_values = Vec::new();

        if let Some(name) = &request.name {
            updates.push("name = ?".to_string());
            param_values.push(name.clone());
        }
        if let Some(prompt_text) = &request.prompt_text {
            updates.push("prompt_text = ?".to_string());
            param_values.push(prompt_text.clone());
        }
        if let Some(description) = &request.description {
            updates.push("description = ?".to_string());
            param_values.push(description.clone());
        }
        if let Some(is_active) = request.is_active {
            updates.push("is_active = ?".to_string());
            param_values.push(if is_active { "1" } else { "0" }.to_string());
        }
        if let Some(sort_order) = request.sort_order {
            updates.push("sort_order = ?".to_string());
            param_values.push(sort_order.to_string());
        }

        if updates.is_empty() {
            // 如果没有更新字段，直接返回当前记录
            return self.get_by_id(id).await;
        }

        updates.push("updated_at = ?".to_string());
        param_values.push(Utc::now().to_rfc3339());
        param_values.push(id.to_string());

        let sql = format!(
            "UPDATE ai_classifications SET {} WHERE id = ?",
            updates.join(", ")
        );

        // 执行更新
        {
            let conn = self.database.get_connection();
            let conn = conn.lock().unwrap();

            // 构建参数引用
            let param_refs: Vec<&dyn rusqlite::ToSql> = param_values.iter()
                .map(|v| v as &dyn rusqlite::ToSql)
                .collect();

            conn.execute(&sql, &param_refs[..])?;
        }

        self.get_by_id(id).await
    }

    /// 删除AI分类
    pub async fn delete(&self, id: &str) -> Result<bool> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let rows_affected = conn.execute(
            "DELETE FROM ai_classifications WHERE id = ?1",
            params![id],
        )?;

        Ok(rows_affected > 0)
    }

    /// 根据名称检查分类是否存在
    pub async fn exists_by_name(&self, name: &str, exclude_id: Option<&str>) -> Result<bool> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let exists = if let Some(exclude_id) = exclude_id {
            conn.query_row(
                "SELECT 1 FROM ai_classifications WHERE name = ?1 AND id != ?2",
                params![name, exclude_id],
                |_| Ok(true)
            ).unwrap_or(false)
        } else {
            conn.query_row(
                "SELECT 1 FROM ai_classifications WHERE name = ?1",
                params![name],
                |_| Ok(true)
            ).unwrap_or(false)
        };

        Ok(exists)
    }

    /// 获取分类总数
    pub async fn count(&self, active_only: Option<bool>) -> Result<i64> {
        let conn = self.database.get_connection();
        let conn = conn.lock().unwrap();

        let count = if let Some(active_only) = active_only {
            if active_only {
                conn.query_row(
                    "SELECT COUNT(*) FROM ai_classifications WHERE is_active = ?1",
                    params![1], // SQLite中布尔值存储为INTEGER
                    |row| row.get(0)
                )?
            } else {
                conn.query_row(
                    "SELECT COUNT(*) FROM ai_classifications",
                    [],
                    |row| row.get(0)
                )?
            }
        } else {
            conn.query_row(
                "SELECT COUNT(*) FROM ai_classifications",
                [],
                |row| row.get(0)
            )?
        };

        Ok(count)
    }

    /// 将数据库行转换为AI分类模型
    fn row_to_classification(&self, row: &Row) -> rusqlite::Result<AiClassification> {
        let created_at_str: String = row.get(6)?;
        let updated_at_str: String = row.get(7)?;

        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|_e| rusqlite::Error::InvalidColumnType(6, "created_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        let updated_at = DateTime::parse_from_rfc3339(&updated_at_str)
            .map_err(|_e| rusqlite::Error::InvalidColumnType(7, "updated_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        // SQLite中布尔值存储为INTEGER (0/1)，需要转换
        let is_active_int: i32 = row.get(4)?;
        let is_active = is_active_int != 0;

        Ok(AiClassification {
            id: row.get(0)?,
            name: row.get(1)?,
            prompt_text: row.get(2)?,
            description: row.get(3)?,
            is_active,
            sort_order: row.get(5)?,
            created_at,
            updated_at,
        })
    }
}
