#[cfg(test)]
mod watermark_tests {
    use crate::data::models::watermark::*;
    use crate::data::repositories::watermark_template_repository::WatermarkTemplateRepository;
    use crate::infrastructure::database::Database;
    use std::sync::Arc;
    use tempfile::TempDir;

    /// 创建测试数据库
    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() -> WatermarkTemplate {
        WatermarkTemplate {
            id: "test_template_1".to_string(),
            name: "测试水印".to_string(),
            file_path: "/tmp/test_watermark.png".to_string(),
            thumbnail_path: Some("/tmp/test_watermark_thumb.jpg".to_string()),
            category: WatermarkCategory::Logo,
            watermark_type: WatermarkType::Image,
            file_size: 1024,
            width: Some(200),
            height: Some(100),
            description: Some("测试用水印模板".to_string()),
            tags: vec!["test".to_string(), "logo".to_string()],
            is_active: true,
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
        }
    }

    /// 创建测试检测配置
    fn create_test_detection_config() -> WatermarkDetectionConfig {
        WatermarkDetectionConfig {
            similarity_threshold: 0.8,
            min_watermark_size: (32, 32),
            max_watermark_size: (512, 512),
            detection_regions: vec![DetectionRegion::Corners, DetectionRegion::Center],
            frame_sample_rate: 30,
            methods: vec![DetectionMethod::TemplateMatching, DetectionMethod::EdgeDetection],
            template_ids: None,
        }
    }

    /// 创建测试移除配置
    fn create_test_removal_config() -> WatermarkRemovalConfig {
        WatermarkRemovalConfig {
            method: RemovalMethod::Blurring,
            quality_level: QualityLevel::Medium,
            preserve_aspect_ratio: true,
            target_regions: None,
            inpainting_model: None,
            blur_radius: Some(5.0),
            crop_margin: Some(10),
        }
    }

    /// 创建测试添加配置
    fn create_test_addition_config() -> WatermarkConfig {
        WatermarkConfig {
            watermark_type: WatermarkType::Image,
            position: WatermarkPosition::BottomRight,
            opacity: 0.8,
            scale: 1.0,
            rotation: 0.0,
            animation: None,
            blend_mode: BlendMode::Normal,
            quality_level: QualityLevel::Medium,
        }
    }

    #[tokio::test]
    async fn test_watermark_template_repository_crud() {
        let database = create_test_database();
        let repository = Arc::new(WatermarkTemplateRepository::new(database));
        let template = create_test_template();

        // 测试创建
        let result = repository.create(&template);
        assert!(result.is_ok(), "创建水印模板失败: {:?}", result.err());

        // 测试查询
        let retrieved = repository.get_by_id(&template.id).unwrap();
        assert!(retrieved.is_some(), "查询水印模板失败");
        let retrieved_template = retrieved.unwrap();
        assert_eq!(retrieved_template.id, template.id);
        assert_eq!(retrieved_template.name, template.name);

        // 测试更新
        let mut updated_template = retrieved_template.clone();
        updated_template.name = "更新后的水印".to_string();
        updated_template.updated_at = chrono::Utc::now();
        
        let update_result = repository.update(&updated_template);
        assert!(update_result.is_ok(), "更新水印模板失败: {:?}", update_result.err());

        // 验证更新
        let updated_retrieved = repository.get_by_id(&template.id).unwrap().unwrap();
        assert_eq!(updated_retrieved.name, "更新后的水印");

        // 测试删除
        let delete_result = repository.delete(&template.id);
        assert!(delete_result.is_ok(), "删除水印模板失败: {:?}", delete_result.err());

        // 验证删除
        let deleted_check = repository.get_by_id(&template.id).unwrap();
        assert!(deleted_check.is_none(), "水印模板应该已被删除");
    }

    #[tokio::test]
    async fn test_watermark_template_search() {
        let database = create_test_database();
        let repository = Arc::new(WatermarkTemplateRepository::new(database));

        // 创建多个测试模板
        let mut template1 = create_test_template();
        template1.id = "template_1".to_string();
        template1.name = "Logo水印".to_string();
        template1.category = WatermarkCategory::Logo;

        let mut template2 = create_test_template();
        template2.id = "template_2".to_string();
        template2.name = "版权水印".to_string();
        template2.category = WatermarkCategory::Copyright;

        let mut template3 = create_test_template();
        template3.id = "template_3".to_string();
        template3.name = "签名水印".to_string();
        template3.category = WatermarkCategory::Signature;
        template3.watermark_type = WatermarkType::Text;

        // 插入模板
        repository.create(&template1).unwrap();
        repository.create(&template2).unwrap();
        repository.create(&template3).unwrap();

        // 测试按分类查询
        let logo_templates = repository.get_by_category(&WatermarkCategory::Logo).unwrap();
        assert_eq!(logo_templates.len(), 1);
        assert_eq!(logo_templates[0].name, "Logo水印");

        // 测试按类型查询
        let text_templates = repository.get_by_type(&WatermarkType::Text).unwrap();
        assert_eq!(text_templates.len(), 1);
        assert_eq!(text_templates[0].name, "签名水印");

        // 测试搜索
        let search_results = repository.search("水印").unwrap();
        assert_eq!(search_results.len(), 3);

        let logo_search = repository.search("Logo").unwrap();
        assert_eq!(logo_search.len(), 1);
        assert_eq!(logo_search[0].name, "Logo水印");
    }

    #[test]
    fn test_watermark_detection_config_validation() {
        let config = create_test_detection_config();
        
        // 验证阈值范围
        assert!(config.similarity_threshold >= 0.0 && config.similarity_threshold <= 1.0);
        
        // 验证尺寸设置
        assert!(config.min_watermark_size.0 > 0);
        assert!(config.min_watermark_size.1 > 0);
        assert!(config.max_watermark_size.0 >= config.min_watermark_size.0);
        assert!(config.max_watermark_size.1 >= config.min_watermark_size.1);
        
        // 验证采样率
        assert!(config.frame_sample_rate > 0);
        
        // 验证检测方法不为空
        assert!(!config.methods.is_empty());
    }

    #[test]
    fn test_watermark_removal_config_validation() {
        let config = create_test_removal_config();
        
        // 验证模糊半径
        if let Some(blur_radius) = config.blur_radius {
            assert!(blur_radius > 0.0);
        }
        
        // 验证裁剪边距
        if let Some(crop_margin) = config.crop_margin {
            assert!(crop_margin > 0);
        }
    }

    #[test]
    fn test_watermark_addition_config_validation() {
        let config = create_test_addition_config();
        
        // 验证透明度范围
        assert!(config.opacity >= 0.0 && config.opacity <= 1.0);
        
        // 验证缩放比例
        assert!(config.scale > 0.0);
        
        // 验证旋转角度范围
        assert!(config.rotation >= -360.0 && config.rotation <= 360.0);
    }

    #[test]
    fn test_watermark_position_calculation() {
        // 测试固定位置
        let positions = vec![
            WatermarkPosition::TopLeft,
            WatermarkPosition::TopRight,
            WatermarkPosition::BottomLeft,
            WatermarkPosition::BottomRight,
            WatermarkPosition::Center,
        ];

        for position in positions {
            // 这里应该调用实际的位置计算函数
            // 由于函数在服务中是私有的，这里只做概念验证
            match position {
                WatermarkPosition::TopLeft => {
                    // 应该返回 (10, 10) 或类似的左上角位置
                }
                WatermarkPosition::BottomRight => {
                    // 应该返回接近 (video_width - watermark_width, video_height - watermark_height) 的位置
                }
                _ => {}
            }
        }
    }

    #[test]
    fn test_batch_progress_calculation() {
        let mut progress = BatchProgress {
            total_items: 10,
            processed_items: 3,
            failed_items: 1,
            current_item: Some("material_4".to_string()),
            progress_percentage: 0.0,
            estimated_remaining_ms: None,
            errors: vec!["Error 1".to_string()],
            detection_results: Vec::new(),
            processing_results: Vec::new(),
        };

        // 计算进度百分比
        progress.progress_percentage = (progress.processed_items as f32 / progress.total_items as f32) * 100.0;
        assert_eq!(progress.progress_percentage, 30.0);

        // 验证错误计数
        assert_eq!(progress.errors.len(), 1);
        assert_eq!(progress.failed_items, 1);
    }

    #[test]
    fn test_watermark_error_types() {
        use crate::business::errors::watermark_errors::*;

        // 测试错误创建
        let detection_error = WatermarkError::detection_failed("检测算法失败");
        assert_eq!(detection_error.error_type(), "detection_failed");
        assert!(!detection_error.is_retryable());
        assert!(detection_error.is_system_error());

        let template_error = WatermarkError::template_not_found("template_123");
        assert_eq!(template_error.error_type(), "template_not_found");
        assert!(!template_error.is_retryable());
        assert!(template_error.is_user_error());

        let network_error = WatermarkError::network_error("http://example.com", "连接超时");
        assert_eq!(network_error.error_type(), "network_error");
        assert!(network_error.is_retryable());
        assert!(!network_error.is_user_error());
    }

    #[test]
    fn test_error_severity_levels() {
        use crate::business::errors::watermark_errors::*;

        let validation_error = WatermarkError::validation_error("opacity", "1.5", "值超出范围");
        assert_eq!(validation_error.severity(), ErrorSeverity::Warning);

        let template_error = WatermarkError::template_not_found("template_123");
        assert_eq!(template_error.severity(), ErrorSeverity::Error);

        let internal_error = WatermarkError::internal_error("系统内部错误");
        assert_eq!(internal_error.severity(), ErrorSeverity::Critical);

        let cancelled_error = WatermarkError::task_cancelled("task_123");
        assert_eq!(cancelled_error.severity(), ErrorSeverity::Info);
    }

    #[test]
    fn test_error_context() {
        use crate::business::errors::watermark_errors::*;

        let context = ErrorContext::new("watermark_detection")
            .with_material_id("material_123")
            .with_template_id("template_456")
            .with_file_path("/path/to/video.mp4")
            .with_info("algorithm", "template_matching")
            .with_info("threshold", "0.8");

        assert_eq!(context.operation, "watermark_detection");
        assert_eq!(context.material_id, Some("material_123".to_string()));
        assert_eq!(context.template_id, Some("template_456".to_string()));
        assert_eq!(context.file_path, Some("/path/to/video.mp4".to_string()));
        assert_eq!(context.additional_info.get("algorithm"), Some(&"template_matching".to_string()));
        assert_eq!(context.additional_info.get("threshold"), Some(&"0.8".to_string()));
    }

    #[tokio::test]
    async fn test_watermark_template_stats() {
        let database = create_test_database();
        let repository = Arc::new(WatermarkTemplateRepository::new(database));

        // 创建不同类型的模板
        let mut template1 = create_test_template();
        template1.id = "template_1".to_string();
        template1.category = WatermarkCategory::Logo;
        template1.watermark_type = WatermarkType::Image;
        template1.file_size = 1000;

        let mut template2 = create_test_template();
        template2.id = "template_2".to_string();
        template2.category = WatermarkCategory::Copyright;
        template2.watermark_type = WatermarkType::Text;
        template2.file_size = 500;

        repository.create(&template1).unwrap();
        repository.create(&template2).unwrap();

        // 获取统计信息
        let stats = repository.get_stats().unwrap();
        
        assert_eq!(stats["total_templates"], 2);
        assert_eq!(stats["total_size"], 1500);
        
        // 验证分类统计
        let by_category = &stats["by_category"];
        assert!(by_category.get("\"Logo\"").is_some());
        assert!(by_category.get("\"Copyright\"").is_some());
        
        // 验证类型统计
        let by_type = &stats["by_type"];
        assert!(by_type.get("\"Image\"").is_some());
        assert!(by_type.get("\"Text\"").is_some());
    }

    #[test]
    fn test_watermark_template_name_validation() {
        let database = create_test_database();
        let repository = Arc::new(WatermarkTemplateRepository::new(database));
        let template = create_test_template();

        // 创建模板
        repository.create(&template).unwrap();

        // 测试名称冲突检查
        let name_exists = repository.name_exists(&template.name, None).unwrap();
        assert!(name_exists, "应该检测到名称已存在");

        // 测试排除自身的名称检查
        let name_exists_exclude_self = repository.name_exists(&template.name, Some(&template.id)).unwrap();
        assert!(!name_exists_exclude_self, "排除自身时不应该检测到名称冲突");

        // 测试不存在的名称
        let new_name_exists = repository.name_exists("不存在的名称", None).unwrap();
        assert!(!new_name_exists, "不存在的名称不应该被检测为已存在");
    }
}
