use anyhow::{anyhow, Result};
use rusqlite::{params, Row};
use std::sync::Arc;
use chrono::{DateTime, Utc};
use tracing::warn;

use crate::data::models::outfit_image::{
    OutfitImageRecord, OutfitImageStatus, ProductImage, OutfitImage, OutfitImageStats
};
use crate::infrastructure::database::Database;

/// 穿搭图片仓储
/// 遵循 Tauri 开发规范的数据访问层设计原则
#[derive(Clone)]
pub struct OutfitImageRepository {
    database: Arc<Database>,
}

impl OutfitImageRepository {
    pub fn new(database: Arc<Database>) -> Self {
        Self { database }
    }

    /// 初始化数据库表（强制使用连接池）
    pub fn init_tables(&self) -> Result<()> {
        // 表创建和索引创建现在通过迁移系统处理
        // 这个方法保留用于未来可能的初始化逻辑
        Ok(())
    }

    /// 创建穿搭图片生成记录
    pub fn create_record(&self, record: &OutfitImageRecord) -> Result<()> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        let result_urls_json = serde_json::to_string(&record.result_urls)
            .map_err(|e| anyhow!("序列化result_urls失败: {}", e))?;

        conn.execute(
            r#"
            INSERT INTO outfit_image_records (
                id, model_id, model_image_id, generation_prompt, status, progress,
                result_urls, error_message, created_at, started_at, completed_at, duration_ms, comfyui_prompt_id
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
            "#,
            params![
                record.id,
                record.model_id,
                record.model_image_id,
                record.generation_prompt,
                record.status.to_string(),
                record.progress,
                result_urls_json,
                record.error_message,
                record.created_at.to_rfc3339(),
                record.started_at.map(|dt| dt.to_rfc3339()),
                record.completed_at.map(|dt| dt.to_rfc3339()),
                record.duration_ms,
                record.comfyui_prompt_id,
            ],
        ).map_err(|e| anyhow!("创建穿搭图片记录失败: {}", e))?;

        Ok(())
    }

    /// 在事务中创建记录和商品图片（强制使用连接池）
    pub fn create_record_with_products(&self, record: &OutfitImageRecord) -> Result<()> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        // 使用连接池获取连接（带重试机制）
        let mut retry_count = 0;
        let max_retries = 3;

        while retry_count < max_retries {
            match self.database.try_acquire_from_pool() {
                Ok(Some(pooled_conn)) => {
                    println!("✅ 成功从连接池获取连接 (尝试 {}/{})", retry_count + 1, max_retries);
                    return self.execute_with_pooled_connection(record, pooled_conn);
                },
                Ok(None) => {
                    retry_count += 1;
                    if retry_count < max_retries {
                        println!("⚠️ 连接池暂无可用连接，等待 200ms 后重试 ({}/{})", retry_count, max_retries);
                        std::thread::sleep(std::time::Duration::from_millis(200));
                    }
                },
                Err(e) => {
                    return Err(anyhow!("连接池获取失败: {}", e));
                }
            }
        }

        // 如果重试失败，使用阻塞方式获取连接池连接
        match self.database.acquire_from_pool() {
            Ok(pooled_conn) => {
                println!("✅ 阻塞方式获取连接池连接成功");
                self.execute_with_pooled_connection(record, pooled_conn)
            },
            Err(e) => {
                Err(anyhow!("阻塞获取连接池连接失败: {}", e))
            }
        }
    }

    /// 使用连接池连接执行操作
    fn execute_with_pooled_connection(&self, record: &OutfitImageRecord, pooled_conn: crate::infrastructure::connection_pool::PooledConnectionHandle) -> Result<()> {

        // 开始事务
        let tx = pooled_conn.unchecked_transaction().map_err(|e| anyhow!("开始事务失败: {}", e))?;

        self.execute_transaction_with_tx(record, &tx)?;

        // 提交事务
        tx.commit().map_err(|e| anyhow!("提交事务失败: {}", e))?;

        Ok(())
    }

    /// 使用连接句柄执行操作
    fn execute_with_connection_handle(&self, record: &OutfitImageRecord, conn_handle: crate::infrastructure::database::ConnectionHandle) -> Result<()> {

        // 开始事务
        let tx = conn_handle.unchecked_transaction().map_err(|e| anyhow!("开始事务失败: {}", e))?;

        self.execute_transaction_with_tx(record, &tx)?;

        // 提交事务
        tx.commit().map_err(|e| anyhow!("提交事务失败: {}", e))?;

        Ok(())
    }

    /// 带超时机制的创建方法（最后手段）
    fn create_with_timeout(&self, record: &OutfitImageRecord) -> Result<()> {
        use std::time::{Duration, Instant};

        let start = Instant::now();
        let timeout = Duration::from_secs(5); // 减少到5秒超时

        loop {
            match self.database.try_get_connection() {
                Some(conn) => {
                    println!("✅ 强制获取数据库连接成功，开始事务...");
                    return self.execute_transaction(record, conn);
                },
                None => {
                    if start.elapsed() >= timeout {
                        return Err(anyhow!("获取数据库连接超时（5秒）- 可能存在死锁，请重启应用"));
                    }

                    println!("⏳ 连接仍被占用，等待 100ms 后重试... (已等待 {:?})", start.elapsed());
                    std::thread::sleep(Duration::from_millis(100));
                }
            }
        }
    }

    /// 执行事务操作（使用MutexGuard）
    fn execute_transaction(&self, record: &OutfitImageRecord, conn: std::sync::MutexGuard<rusqlite::Connection>) -> Result<()> {
        // 开始事务
        let tx = conn.unchecked_transaction().map_err(|e| anyhow!("开始事务失败: {}", e))?;

        self.execute_transaction_with_tx(record, &tx)?;

        // 提交事务
        tx.commit().map_err(|e| anyhow!("提交事务失败: {}", e))?;

        println!("✅ MutexGuard事务提交成功");
        Ok(())
    }

    /// 通用事务执行方法
    fn execute_transaction_with_tx(&self, record: &OutfitImageRecord, tx: &rusqlite::Transaction) -> Result<()> {
        // 创建主记录
        let result_urls_json = serde_json::to_string(&record.result_urls)
            .map_err(|e| anyhow!("序列化result_urls失败: {}", e))?;

        tx.execute(
            r#"
            INSERT INTO outfit_image_records (
                id, model_id, model_image_id, generation_prompt, status, progress,
                result_urls, error_message, created_at, started_at, completed_at, duration_ms
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)
            "#,
            params![
                record.id,
                record.model_id,
                record.model_image_id,
                record.generation_prompt,
                record.status.to_string(),
                record.progress,
                result_urls_json,
                record.error_message,
                record.created_at.to_rfc3339(),
                record.started_at.map(|dt| dt.to_rfc3339()),
                record.completed_at.map(|dt| dt.to_rfc3339()),
                record.duration_ms,
            ],
        ).map_err(|e| anyhow!("创建穿搭图片记录失败: {}", e))?;

        println!("📷 创建商品图片记录，共 {} 个...", record.product_images.len());
        // 创建商品图片记录
        for (index, product_image) in record.product_images.iter().enumerate() {
            tx.execute(
                r#"
                INSERT INTO product_images (
                    id, outfit_record_id, file_path, file_name, file_size,
                    upload_url, description, created_at
                ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
                "#,
                params![
                    product_image.id,
                    product_image.outfit_record_id,
                    product_image.file_path,
                    product_image.file_name,
                    product_image.file_size,
                    product_image.upload_url,
                    product_image.description,
                    product_image.created_at.to_rfc3339(),
                ],
            ).map_err(|e| anyhow!("创建商品图片失败: {}", e))?;
        }

        Ok(())
    }


    /// 更新穿搭图片生成记录（强制使用连接池）
    pub fn update_record(&self, record: &OutfitImageRecord) -> Result<()> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        
        let result_urls_json = serde_json::to_string(&record.result_urls)
            .map_err(|e| anyhow!("序列化result_urls失败: {}", e))?;

        pooled_conn.execute(
            r#"
            UPDATE outfit_image_records SET
                status = ?2, progress = ?3, result_urls = ?4, error_message = ?5,
                started_at = ?6, completed_at = ?7, duration_ms = ?8
            WHERE id = ?1
            "#,
            params![
                record.id,
                record.status.to_string(),
                record.progress,
                result_urls_json,
                record.error_message,
                record.started_at.map(|dt| dt.to_rfc3339()),
                record.completed_at.map(|dt| dt.to_rfc3339()),
                record.duration_ms,
            ],
        ).map_err(|e| anyhow!("更新穿搭图片记录失败: {}", e))?;


        Ok(())
    }

    /// 根据ID获取穿搭图片生成记录
    pub fn get_record_by_id(&self, id: &str) -> Result<Option<OutfitImageRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        let mut stmt = conn.prepare(
            r#"
            SELECT id, model_id, model_image_id, generation_prompt, status, progress,
                   result_urls, error_message, created_at, started_at, completed_at, duration_ms, comfyui_prompt_id
            FROM outfit_image_records WHERE id = ?1
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let record_iter = stmt.query_map(params![id], |row| {
            self.row_to_record(row)
        }).map_err(|e| anyhow!("查询穿搭图片记录失败: {}", e))?;

        for record in record_iter {
            let mut record = record.map_err(|e| anyhow!("解析记录失败: {}", e))?;
            
            // 加载关联的商品图片和穿搭图片
            record.product_images = self.get_product_images_by_record_id(&record.id)?;
            record.outfit_images = self.get_outfit_images_by_record_id(&record.id)?;
            
            return Ok(Some(record));
        }

        Ok(None)
    }

    /// 根据 ComfyUI prompt_id 获取穿搭图片生成记录
    pub fn get_record_by_comfyui_prompt_id(&self, prompt_id: &str) -> Result<Option<OutfitImageRecord>> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let conn = self
            .database
            .acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;
        let mut stmt = conn.prepare(
            r#"
            SELECT id, model_id, model_image_id, generation_prompt, status, progress,
                   result_urls, error_message, created_at, started_at, completed_at, duration_ms, comfyui_prompt_id
            FROM outfit_image_records WHERE comfyui_prompt_id = ?1
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let record_iter = stmt.query_map(params![prompt_id], |row| {
            self.row_to_record(row)
        }).map_err(|e| anyhow!("查询穿搭图片记录失败: {}", e))?;

        for record_result in record_iter {
            let mut record = record_result.map_err(|e| anyhow!("解析记录失败: {}", e))?;

            // 加载关联的商品图片和穿搭图片
            record.product_images = self.get_product_images_by_record_id(&record.id)?;
            record.outfit_images = self.get_outfit_images_by_record_id(&record.id)?;

            return Ok(Some(record));
        }

        Ok(None)
    }

    /// 根据模特ID获取穿搭图片生成记录列表（强制使用连接池）
    pub fn get_records_by_model_id(&self, model_id: &str) -> Result<Vec<OutfitImageRecord>> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT id, model_id, model_image_id, generation_prompt, status, progress,
                   result_urls, error_message, created_at, started_at, completed_at, duration_ms, comfyui_prompt_id
            FROM outfit_image_records
            WHERE model_id = ?1
            ORDER BY created_at DESC
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let record_iter = stmt.query_map(params![model_id], |row| {
            self.row_to_record(row)
        }).map_err(|e| anyhow!("查询穿搭图片记录失败: {}", e))?;

        let mut records = Vec::new();
        for record_result in record_iter {
            let mut record = record_result.map_err(|e| anyhow!("解析记录失败: {}", e))?;

            // 加载关联的商品图片
            record.product_images = self.get_product_images_by_record_id(&record.id)?;

            // 加载关联的穿搭图片
            record.outfit_images = self.get_outfit_images_by_record_id(&record.id)?;

            records.push(record);
        }

        Ok(records)
    }

    /// 根据模特ID获取分页的穿搭图片生成记录列表
    pub fn get_records_by_model_id_paginated(&self, model_id: &str, limit: u32, offset: u32) -> Result<Vec<OutfitImageRecord>> {
        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT id, model_id, model_image_id, generation_prompt, status, progress,
                   result_urls, error_message, created_at, started_at, completed_at, duration_ms, comfyui_prompt_id
            FROM outfit_image_records
            WHERE model_id = ?1
            ORDER BY created_at DESC
            LIMIT ?2 OFFSET ?3
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let record_iter = stmt.query_map(params![model_id, limit, offset], |row| {
            self.row_to_record(row)
        }).map_err(|e| anyhow!("查询穿搭图片记录失败: {}", e))?;

        let mut records = Vec::new();
        for record_result in record_iter {
            let mut record = record_result.map_err(|e| anyhow!("解析记录失败: {}", e))?;

            // 加载关联的商品图片
            record.product_images = self.get_product_images_by_record_id(&record.id)?;

            // 加载关联的穿搭图片
            record.outfit_images = self.get_outfit_images_by_record_id(&record.id)?;

            records.push(record);
        }

        Ok(records)
    }

    /// 获取模特的穿搭图片记录总数
    pub fn get_records_count_by_model_id(&self, model_id: &str) -> Result<u32> {
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let count: u32 = pooled_conn.query_row(
            "SELECT COUNT(*) FROM outfit_image_records WHERE model_id = ?1",
            params![model_id],
            |row| row.get(0)
        ).map_err(|e| anyhow!("查询记录总数失败: {}", e))?;

        Ok(count)
    }

    /// 删除穿搭图片生成记录（强制使用连接池）
    pub fn delete_record(&self, id: &str) -> Result<()> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        pooled_conn.execute(
            "DELETE FROM outfit_image_records WHERE id = ?1",
            params![id],
        ).map_err(|e| anyhow!("删除穿搭图片记录失败: {}", e))?;

        Ok(())
    }

    /// 创建商品图片（强制使用连接池）
    pub fn create_product_image(&self, product_image: &ProductImage) -> Result<()> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        pooled_conn.execute(
            r#"
            INSERT INTO product_images (
                id, outfit_record_id, file_path, file_name, file_size,
                upload_url, description, created_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
            "#,
            params![
                product_image.id,
                product_image.outfit_record_id,
                product_image.file_path,
                product_image.file_name,
                product_image.file_size,
                product_image.upload_url,
                product_image.description,
                product_image.created_at.to_rfc3339(),
            ],
        ).map_err(|e| anyhow!("创建商品图片失败: {}", e))?;

        Ok(())
    }

    /// 根据记录ID获取商品图片列表（强制使用连接池）
    pub fn get_product_images_by_record_id(&self, record_id: &str) -> Result<Vec<ProductImage>> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT id, outfit_record_id, file_path, file_name, file_size,
                   upload_url, description, created_at
            FROM product_images
            WHERE outfit_record_id = ?1
            ORDER BY created_at ASC
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let image_iter = stmt.query_map(params![record_id], |row| {
            self.row_to_product_image(row)
        }).map_err(|e| anyhow!("查询商品图片失败: {}", e))?;

        let mut images = Vec::new();
        for image in image_iter {
            images.push(image.map_err(|e| anyhow!("解析商品图片失败: {}", e))?);
        }

        Ok(images)
    }

    /// 创建穿搭图片（强制使用连接池）
    pub fn create_outfit_image(&self, outfit_image: &OutfitImage) -> Result<()> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let tags_json = serde_json::to_string(&outfit_image.tags)
            .map_err(|e| anyhow!("序列化tags失败: {}", e))?;

        pooled_conn.execute(
            r#"
            INSERT INTO outfit_images (
                id, outfit_record_id, image_url, local_path, image_index,
                description, tags, is_favorite, created_at
            ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
            "#,
            params![
                outfit_image.id,
                outfit_image.outfit_record_id,
                outfit_image.image_url,
                outfit_image.local_path,
                outfit_image.image_index,
                outfit_image.description,
                tags_json,
                outfit_image.is_favorite,
                outfit_image.created_at.to_rfc3339(),
            ],
        ).map_err(|e| anyhow!("创建穿搭图片失败: {}", e))?;

        Ok(())
    }

    /// 根据记录ID获取穿搭图片列表（强制使用连接池）
    pub fn get_outfit_images_by_record_id(&self, record_id: &str) -> Result<Vec<OutfitImage>> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT id, outfit_record_id, image_url, local_path, image_index,
                   description, tags, is_favorite, created_at
            FROM outfit_images
            WHERE outfit_record_id = ?1
            ORDER BY image_index ASC
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let image_iter = stmt.query_map(params![record_id], |row| {
            self.row_to_outfit_image(row)
        }).map_err(|e| anyhow!("查询穿搭图片失败: {}", e))?;

        let mut images = Vec::new();
        for image in image_iter {
            images.push(image.map_err(|e| anyhow!("解析穿搭图片失败: {}", e))?);
        }

        Ok(images)
    }

    /// 获取模特的穿搭图片统计信息（强制使用连接池）
    pub fn get_stats_by_model_id(&self, model_id: &str) -> Result<OutfitImageStats> {

        // 🚨 强制使用连接池，避免死锁
        if !self.database.has_pool() {
            return Err(anyhow!("连接池未启用，无法安全执行数据库操作"));
        }

        let pooled_conn = self.database.acquire_from_pool()
            .map_err(|e| anyhow!("获取连接池连接失败: {}", e))?;

        // 获取记录统计
        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT
                COUNT(*) as total_records,
                COALESCE(SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END), 0) as pending_records,
                COALESCE(SUM(CASE WHEN status = 'processing' THEN 1 ELSE 0 END), 0) as processing_records,
                COALESCE(SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END), 0) as completed_records,
                COALESCE(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END), 0) as failed_records
            FROM outfit_image_records WHERE model_id = ?1
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let (total_records, pending_records, processing_records, completed_records, failed_records) =
            stmt.query_row(params![model_id], |row| {
                Ok((
                    row.get::<_, u32>(0)?,
                    row.get::<_, u32>(1)?,
                    row.get::<_, u32>(2)?,
                    row.get::<_, u32>(3)?,
                    row.get::<_, u32>(4)?,
                ))
            }).map_err(|e| anyhow!("查询记录统计失败: {}", e))?;

        // 获取图片统计
        let mut stmt = pooled_conn.prepare(
            r#"
            SELECT
                COUNT(*) as total_images,
                COALESCE(SUM(CASE WHEN is_favorite = 1 THEN 1 ELSE 0 END), 0) as favorite_images
            FROM outfit_images oi
            JOIN outfit_image_records oir ON oi.outfit_record_id = oir.id
            WHERE oir.model_id = ?1
            "#,
        ).map_err(|e| anyhow!("准备查询语句失败: {}", e))?;

        let (total_images, favorite_images) = stmt.query_row(params![model_id], |row| {
            Ok((
                row.get::<_, u32>(0)?,
                row.get::<_, u32>(1)?,
            ))
        }).map_err(|e| anyhow!("查询图片统计失败: {}", e))?;

        Ok(OutfitImageStats {
            total_records,
            total_images,
            favorite_images,
            pending_records,
            processing_records,
            completed_records,
            failed_records,
        })
    }

    /// 将数据库行转换为OutfitImageRecord
    fn row_to_record(&self, row: &Row) -> rusqlite::Result<OutfitImageRecord> {
        let result_urls_json: String = row.get(6)?;
        let result_urls: Vec<String> = serde_json::from_str(&result_urls_json)
            .unwrap_or_default();

        let created_at_str: String = row.get(8)?;
        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        let started_at = if let Ok(started_at_str) = row.get::<_, Option<String>>(9) {
            started_at_str.and_then(|s| DateTime::parse_from_rfc3339(&s).ok().map(|dt| dt.with_timezone(&Utc)))
        } else {
            None
        };

        let completed_at = if let Ok(completed_at_str) = row.get::<_, Option<String>>(10) {
            completed_at_str.and_then(|s| DateTime::parse_from_rfc3339(&s).ok().map(|dt| dt.with_timezone(&Utc)))
        } else {
            None
        };

        Ok(OutfitImageRecord {
            id: row.get(0)?,
            model_id: row.get(1)?,
            model_image_id: row.get(2)?,
            generation_prompt: row.get(3)?,
            status: OutfitImageStatus::from(row.get::<_, String>(4)?),
            progress: row.get(5)?,
            result_urls,
            error_message: row.get(7)?,
            created_at,
            started_at,
            completed_at,
            duration_ms: row.get(11)?,
            comfyui_prompt_id: row.get(12)?,
            product_images: Vec::new(), // 将在调用方加载
            outfit_images: Vec::new(),  // 将在调用方加载
        })
    }

    /// 将数据库行转换为ProductImage
    fn row_to_product_image(&self, row: &Row) -> rusqlite::Result<ProductImage> {
        let created_at_str: String = row.get(7)?;
        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|_| rusqlite::Error::InvalidColumnType(7, "created_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        Ok(ProductImage {
            id: row.get(0)?,
            outfit_record_id: row.get(1)?,
            file_path: row.get(2)?,
            file_name: row.get(3)?,
            file_size: row.get(4)?,
            upload_url: row.get(5)?,
            description: row.get(6)?,
            created_at,
        })
    }

    /// 将数据库行转换为OutfitImage
    fn row_to_outfit_image(&self, row: &Row) -> rusqlite::Result<OutfitImage> {
        let tags_json: String = row.get(6)?;
        let tags: Vec<String> = serde_json::from_str(&tags_json)
            .unwrap_or_default();

        let created_at_str: String = row.get(8)?;
        let created_at = DateTime::parse_from_rfc3339(&created_at_str)
            .map_err(|_| rusqlite::Error::InvalidColumnType(8, "created_at".to_string(), rusqlite::types::Type::Text))?
            .with_timezone(&Utc);

        Ok(OutfitImage {
            id: row.get(0)?,
            outfit_record_id: row.get(1)?,
            image_url: row.get(2)?,
            local_path: row.get(3)?,
            image_index: row.get(4)?,
            description: row.get(5)?,
            tags,
            is_favorite: row.get(7)?,
            created_at,
        })
    }
}
