//! One-time data seeding logic for initializing the database.

use common_contracts::config_models::{AnalysisModuleConfig, AnalysisTemplateSet, AnalysisTemplateSets};
use sqlx::PgPool;
use std::collections::HashMap;
use tracing::info;

const DEFAULT_ANALYSIS_CONFIG_JSON: &str = include_str!("../../../config/analysis-config.json");
const CONFIG_KEY: &str = "analysis_template_sets";

#[derive(serde::Deserialize)]
struct RawAnalysisConfig {
    analysis_modules: HashMap<String, AnalysisModuleConfig>,
}

/// Seeds the database with default configurations if they don't already exist.
pub async fn seed_data(pool: &PgPool) -> Result<(), sqlx::Error> {
    info!("Checking if default data seeding is required...");

    let mut tx = pool.begin().await?;

    // Check if the 'analysis_template_sets' config already exists.
    let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM system_config WHERE config_key = $1")
        .bind(CONFIG_KEY)
        .fetch_one(&mut *tx)
        .await?;

    if count == 0 {
        info!("No 'analysis_template_sets' config found. Seeding default analysis templates...");

        // 解析当前仓库中的配置文件结构：
        let raw: RawAnalysisConfig = serde_json::from_str(DEFAULT_ANALYSIS_CONFIG_JSON)
            .expect("Failed to parse embedded default analysis config JSON");

        let modules = raw
            .analysis_modules
            .into_iter()
            .map(|(k, mut v)| {
                // Set ID if missing
                if v.id.is_none() {
                    v.id = Some(k.clone());
                }
                (k, v)
            })
            .collect();

        let default_template_set = AnalysisTemplateSet {
            name: "默认分析模板".to_string(),
            modules,
        };

        let mut template_sets = AnalysisTemplateSets::new();
        template_sets.insert("default".to_string(), default_template_set);

        // 仅存储 analysis_template_sets 自身为该 key 的值
        let config_value = serde_json::to_value(&template_sets)
            .expect("Failed to serialize default analysis template sets");

        // Insert the new default config.
        sqlx::query("INSERT INTO system_config (config_key, config_value) VALUES ($1, $2)")
            .bind(CONFIG_KEY)
            .bind(config_value)
            .execute(&mut *tx)
            .await?;

        info!("Successfully seeded default analysis templates.");
    } else {
        info!("Database already seeded. Skipping.");
    }

    tx.commit().await?;

    Ok(())
}
