// 基本测试模块
// 只测试基本的数据结构和简单功能

#[test]
fn test_basic_functionality() {
    // 简单的测试，确保基本功能正常
    assert_eq!(2 + 2, 4);
    assert!(true);
}

#[test]
fn test_workflow_template_model() {
    use crate::data::models::workflow_template::{WorkflowTemplate, WorkflowType};
    use chrono::Utc;
    
    let template = WorkflowTemplate {
        id: Some(1),
        name: "测试模板".to_string(),
        base_name: "test".to_string(),
        version: "1.0".to_string(),
        workflow_type: WorkflowType::OutfitGeneration,
        description: Some("测试描述".to_string()),
        comfyui_workflow_json: serde_json::json!({}),
        ui_config_json: serde_json::json!({}),
        execution_config_json: None,
        input_schema_json: None,
        output_schema_json: None,
        is_active: true,
        is_published: false,
        tags: None,
        category: Some("测试".to_string()),
        author: Some("测试作者".to_string()),
        created_at: Utc::now(),
        updated_at: Utc::now(),
    };
    
    assert_eq!(template.name, "测试模板");
    assert_eq!(template.version, "1.0");
    assert!(template.is_active);
    assert!(!template.is_published);
}

#[test]
fn test_workflow_execution_record_model() {
    use crate::data::models::workflow_execution_record::{WorkflowExecutionRecord, ExecutionStatus};
    use chrono::Utc;
    
    let record = WorkflowExecutionRecord {
        id: Some(1),
        workflow_template_id: 1,
        workflow_name: "测试工作流".to_string(),
        workflow_version: "1.0".to_string(),
        execution_environment_id: Some(1),
        execution_environment_name: Some("测试环境".to_string()),
        status: ExecutionStatus::Pending,
        started_at: Some(Utc::now()),
        completed_at: None,
        duration_seconds: None,
        error_message: None,
        error_details_json: None,
        user_id: Some("test_user".to_string()),
        session_id: Some("test_session".to_string()),
        metadata_json: None,
        tags: None,
        input_data_json: serde_json::json!({}),
        output_data_json: None,
        progress: 0,
        comfyui_prompt_id: None,
        comfyui_workflow_name: None,
        created_at: Utc::now(),
        updated_at: Utc::now(),
    };
    
    assert_eq!(record.workflow_name, "测试工作流");
    assert_eq!(record.status, ExecutionStatus::Pending);
    assert!(record.started_at.is_some());
    assert!(record.completed_at.is_none());
}

#[test]
fn test_workflow_execution_environment_model() {
    use crate::data::models::workflow_execution_environment::{WorkflowExecutionEnvironment, EnvironmentType, HealthStatus};
    use chrono::Utc;
    
    let environment = WorkflowExecutionEnvironment {
        id: Some(1),
        name: "测试环境".to_string(),
        environment_type: EnvironmentType::LocalComfyui,
        description: Some("测试环境描述".to_string()),
        base_url: "http://localhost:8188".to_string(),
        api_key: None,
        connection_config_json: None,
        health_status: HealthStatus::Healthy,
        last_health_check: Some(Utc::now()),
        is_active: true,
        supported_workflow_types: vec!["test".to_string()],
        max_concurrent_jobs: 4,
        priority: 100,
        max_memory_mb: Some(8192),
        max_execution_time_seconds: Some(3600),
        metadata_json: None,
        tags: None,
        is_available: true,
        total_executions: 0,
        failed_executions: 0,
        success_rate: 100.0,
        average_response_time_ms: Some(0),
        created_at: Utc::now(),
        updated_at: Utc::now(),
    };
    
    assert_eq!(environment.name, "测试环境");
    assert_eq!(environment.environment_type, EnvironmentType::LocalComfyui);
    assert_eq!(environment.health_status, HealthStatus::Healthy);
    assert!(environment.is_active);
}

#[test]
fn test_string_operations() {
    let test_string = "Hello, World!";
    assert_eq!(test_string.len(), 13);
    assert!(test_string.contains("World"));
    assert!(test_string.starts_with("Hello"));
}

#[test]
fn test_json_operations() {
    let json_value = serde_json::json!({
        "name": "test",
        "value": 42,
        "active": true
    });

    assert!(json_value.is_object());
    assert_eq!(json_value["name"], "test");
    assert_eq!(json_value["value"], 42);
    assert_eq!(json_value["active"], true);
}

#[tokio::test]
async fn test_database_connection() {
    use crate::infrastructure::database::Database;

    // 测试数据库连接
    let database = Database::new().expect("应该能够创建数据库连接");

    // 运行迁移
    database.run_migrations().expect("应该能够运行数据库迁移");

    // 测试查询工作流模板表
    let conn = database.get_connection();
    let conn = conn.lock().unwrap();

    // 检查表是否存在
    let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='workflow_templates'")
        .expect("应该能够准备查询语句");

    let table_exists = stmt.exists([]).expect("应该能够检查表是否存在");
    assert!(table_exists, "workflow_templates 表应该存在");

    // 检查表结构
    let mut stmt = conn.prepare("PRAGMA table_info(workflow_templates)")
        .expect("应该能够准备表结构查询");

    let column_count = stmt.query_map([], |row| {
        Ok(row.get::<_, String>(1)?) // 获取列名
    }).expect("应该能够查询表结构")
    .collect::<Result<Vec<_>, _>>()
    .expect("应该能够收集列信息")
    .len();

    assert!(column_count > 0, "workflow_templates 表应该有列");
    println!("数据库连接测试通过，workflow_templates 表有 {} 列", column_count);
}

#[tokio::test]
async fn test_workflow_template_repository() {
    use crate::data::repositories::workflow_template_repository::WorkflowTemplateRepository;
    use crate::infrastructure::database::Database;
    use std::sync::Arc;

    // 创建数据库和仓库
    let database = Arc::new(Database::new().expect("应该能够创建数据库"));
    database.run_migrations().expect("应该能够运行迁移");

    // 首先检查数据库中的原始数据
    let conn = database.get_connection();
    let conn = conn.lock().unwrap();

    // 检查表中是否有数据
    let count: i64 = conn.query_row("SELECT COUNT(*) FROM workflow_templates", [], |row| {
        row.get(0)
    }).expect("应该能够查询记录数量");

    println!("数据库中有 {} 条工作流模板记录", count);

    if count > 0 {
        // 检查第一条记录的所有字段
        let mut stmt = conn.prepare("SELECT * FROM workflow_templates LIMIT 1")
            .expect("应该能够准备查询语句");

        let result = stmt.query_row([], |row| {
            println!("第一条记录的所有字段:");
            for i in 0..row.as_ref().column_count() {
                let column_name = row.as_ref().column_name(i).unwrap_or("unknown");
                match row.get_ref(i) {
                    Ok(value) => {
                        match value {
                            rusqlite::types::ValueRef::Null => println!("  {}: NULL", column_name),
                            rusqlite::types::ValueRef::Integer(v) => println!("  {}: {}", column_name, v),
                            rusqlite::types::ValueRef::Real(v) => println!("  {}: {}", column_name, v),
                            rusqlite::types::ValueRef::Text(v) => {
                                let text = std::str::from_utf8(v).unwrap_or("invalid utf8");
                                if text.len() > 100 {
                                    println!("  {}: {} chars, preview: {:?}", column_name, text.len(), &text[..100]);
                                } else {
                                    println!("  {}: {:?}", column_name, text);
                                }
                            },
                            rusqlite::types::ValueRef::Blob(v) => println!("  {}: blob {} bytes", column_name, v.len()),
                        }
                    },
                    Err(e) => println!("  {}: ERROR - {}", column_name, e),
                }
            }
            Ok(())
        });

        if let Err(e) = result {
            println!("查询第一条记录失败: {}", e);
        }
    }

    drop(conn); // 释放连接

    // 现在测试手动解析第一条记录
    if count > 0 {
        let conn = database.get_connection();
        let conn = conn.lock().unwrap();

        let mut stmt = conn.prepare("SELECT * FROM workflow_templates LIMIT 1")
            .expect("应该能够准备查询语句");

        let result = stmt.query_row([], |row| {
            println!("开始手动解析记录...");

            // 逐个字段解析，找出问题所在
            let id: Option<i64> = Some(row.get("id")?);
            println!("✓ ID: {:?}", id);

            let name: String = row.get("name")?;
            println!("✓ Name: {}", name);

            let base_name: String = row.get("base_name")?;
            println!("✓ Base name: {}", base_name);

            let version: String = row.get("version")?;
            println!("✓ Version: {}", version);

            let type_str: String = row.get("type")?;
            println!("✓ Type: {}", type_str);

            let description: Option<String> = row.get("description")?;
            println!("✓ Description: {:?}", description);

            // 测试JSON字段解析
            let comfyui_workflow_json_str: String = row.get("comfyui_workflow_json")?;
            println!("✓ ComfyUI JSON string length: {}", comfyui_workflow_json_str.len());

            // 尝试解析JSON
            match serde_json::from_str::<serde_json::Value>(&comfyui_workflow_json_str) {
                Ok(json) => println!("✓ ComfyUI JSON parsed successfully"),
                Err(e) => println!("✗ ComfyUI JSON parse error: {}", e),
            }

            let ui_config_json_str: String = row.get("ui_config_json")?;
            println!("✓ UI Config JSON string length: {}", ui_config_json_str.len());

            match serde_json::from_str::<serde_json::Value>(&ui_config_json_str) {
                Ok(json) => println!("✓ UI Config JSON parsed successfully"),
                Err(e) => println!("✗ UI Config JSON parse error: {}", e),
            }

            Ok(())
        });

        if let Err(e) = result {
            println!("手动解析失败: {}", e);
        }
    }

    let repo = WorkflowTemplateRepository::new(database);

    // 测试查询所有模板（应该返回空列表而不是错误）
    match repo.find_all(None) {
        Ok(templates) => {
            println!("成功查询工作流模板，数量: {}", templates.len());
            // 空列表是正常的，因为还没有插入数据
        },
        Err(e) => {
            panic!("查询工作流模板失败: {}", e);
        }
    }
}
