#[cfg(test)]
mod template_foreign_key_tests {
    use crate::data::models::template::*;
    use crate::business::services::template_service::TemplateService;
    use crate::infrastructure::database::Database;
    use std::sync::Arc;
    use tempfile::TempDir;
    use chrono::Utc;

    /// 创建测试数据库
    fn create_test_database() -> Arc<Database> {
        let temp_dir = TempDir::new().unwrap();
        let db_path = temp_dir.path().join("test.db");
        Arc::new(Database::new_with_path(db_path.to_str().unwrap()).unwrap())
    }

    /// 创建测试模板
    fn create_test_template() -> Template {
        let template_id = "520B7E9D-FD28-4462-9EF2-ECA0C8F3FFE0".to_string();
        let now = Utc::now();
        
        let mut template = Template::new(
            "模板(2)".to_string(),
            CanvasConfig {
                width: 1920,
                height: 1080,
                ratio: "16:9".to_string(),
            },
            30000000, // 30秒
            30.0,
        );
        
        // 使用固定的模板ID来重现问题
        template.id = template_id.clone();
        
        // 添加测试素材
        let material = TemplateMaterial {
            id: "91669AE3-910D-4bd9-AF85-870E5752A4F8".to_string(),
            template_id: template_id.clone(), // 确保template_id匹配
            original_id: "original_material_1".to_string(),
            name: "测试素材".to_string(),
            material_type: TemplateMaterialType::Video,
            original_path: "/test/path/video.mp4".to_string(),
            remote_url: None,
            file_size: Some(1024000),
            duration: Some(30000000),
            width: Some(1920),
            height: Some(1080),
            upload_status: UploadStatus::Completed,
            file_exists: true,
            upload_success: true,
            metadata: None,
            created_at: now,
            updated_at: now,
        };
        
        template.add_material(material);
        template
    }

    #[tokio::test]
    async fn test_foreign_key_constraint_issue() {
        let database = create_test_database();
        let service = TemplateService::new(database);
        let template = create_test_template();

        println!("模板ID: {}", template.id);
        println!("素材数量: {}", template.materials.len());
        if !template.materials.is_empty() {
            println!("第一个素材ID: {}", template.materials[0].id);
            println!("第一个素材的template_id: {}", template.materials[0].template_id);
        }

        // 尝试保存模板
        let result = service.save_template(&template).await;
        
        match result {
            Ok(_) => {
                println!("✅ 模板保存成功");
                
                // 验证模板是否真的保存成功
                let saved_template = service.get_template_by_id(&template.id).await.unwrap();
                assert!(saved_template.is_some(), "保存后应该能够获取模板");
                
                let saved_template = saved_template.unwrap();
                assert_eq!(saved_template.materials.len(), 1, "应该有一个素材");
                assert_eq!(saved_template.materials[0].id, template.materials[0].id, "素材ID应该匹配");
            }
            Err(e) => {
                println!("❌ 模板保存失败: {}", e);
                
                // 检查是否是外键约束错误
                let error_msg = e.to_string();
                if error_msg.contains("FOREIGN KEY constraint failed") {
                    println!("🔍 确认是外键约束失败错误");
                    
                    // 手动检查数据库状态
                    let database = service.get_database();
                    let conn = database.get_connection();
                    let conn = conn.lock().unwrap();
                    
                    // 检查模板是否存在
                    let template_count: i64 = conn.query_row(
                        "SELECT COUNT(*) FROM templates WHERE id = ?1",
                        rusqlite::params![template.id],
                        |row| row.get(0)
                    ).unwrap_or(0);
                    
                    println!("数据库中模板数量: {}", template_count);
                    
                    // 检查外键约束是否启用
                    let foreign_keys_enabled: i64 = conn.query_row(
                        "PRAGMA foreign_keys",
                        [],
                        |row| row.get(0)
                    ).unwrap_or(0);
                    
                    println!("外键约束是否启用: {}", foreign_keys_enabled);
                }
                
                // 重新抛出错误以便测试失败
                panic!("模板保存失败: {}", e);
            }
        }
    }

    #[tokio::test]
    async fn test_template_id_consistency() {
        let database = create_test_database();
        let _service = TemplateService::new(database);
        let template = create_test_template();

        // 验证模板和素材的ID一致性
        assert!(!template.id.is_empty(), "模板ID不能为空");
        assert!(!template.materials.is_empty(), "应该有素材");
        
        for (index, material) in template.materials.iter().enumerate() {
            assert!(!material.id.is_empty(), "素材ID不能为空 (index: {})", index);
            assert_eq!(
                material.template_id, 
                template.id, 
                "素材的template_id应该与模板ID匹配 (index: {})", 
                index
            );
        }
        
        println!("✅ 模板和素材ID一致性检查通过");
    }
}
