-- ===================================================================
-- 全局配置数据迁移脚本
-- 从 ak_global_configs (key后缀方式) 迁移到 ak_global_config + ak_global_config_translations
-- ===================================================================

-- 1. 备份原有数据
CREATE TABLE IF NOT EXISTS public.ak_global_configs_backup AS 
SELECT * FROM public.ak_global_configs;

-- 2. 创建迁移日志表
CREATE TABLE IF NOT EXISTS public.migration_log (
    id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
    migration_name VARCHAR(100) NOT NULL,
    status VARCHAR(20) NOT NULL, -- 'started', 'completed', 'failed'
    message TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- 记录迁移开始
INSERT INTO public.migration_log (migration_name, status, message)
VALUES ('global_config_migration', 'started', '开始迁移全局配置数据');

-- 3. 迁移函数
CREATE OR REPLACE FUNCTION migrate_config_item(
    p_base_key VARCHAR(100),
    p_category VARCHAR(50),
    p_is_translatable BOOLEAN,
    p_sort_order INTEGER
) RETURNS VOID AS $$
DECLARE
    config_id UUID;
    zh_value TEXT := NULL;
    en_value TEXT := NULL;
    tw_value TEXT := NULL;
    ja_value TEXT := NULL;
    default_val TEXT := NULL;
BEGIN
    -- 获取各语言的值
    IF p_is_translatable THEN
        SELECT config_value INTO zh_value FROM public.ak_global_configs 
        WHERE config_key = p_base_key || '_zh' AND is_active = true;
        
        SELECT config_value INTO en_value FROM public.ak_global_configs 
        WHERE config_key = p_base_key || '_en' AND is_active = true;
        
        SELECT config_value INTO tw_value FROM public.ak_global_configs 
        WHERE config_key = p_base_key || '_tw' AND is_active = true;
        
        SELECT config_value INTO ja_value FROM public.ak_global_configs 
        WHERE config_key = p_base_key || '_ja' AND is_active = true;
        
        -- 使用中文作为默认值
        default_val := zh_value;
    ELSE
        -- 非翻译配置项，直接获取值
        SELECT config_value INTO default_val FROM public.ak_global_configs 
        WHERE config_key = p_base_key AND is_active = true;
    END IF;
    
    -- 插入主配置记录
    INSERT INTO public.ak_global_config (
        config_key, 
        config_category, 
        is_translatable, 
        sort_order,
        default_value
    ) VALUES (
        p_base_key, 
        p_category, 
        p_is_translatable, 
        p_sort_order,
        default_val
    ) ON CONFLICT (config_key) DO UPDATE SET
        config_category = EXCLUDED.config_category,
        is_translatable = EXCLUDED.is_translatable,
        sort_order = EXCLUDED.sort_order,
        default_value = EXCLUDED.default_value,
        updated_at = NOW()
    RETURNING id INTO config_id;
    
    -- 如果需要翻译，插入翻译记录
    IF p_is_translatable THEN
        -- 中文翻译
        IF zh_value IS NOT NULL THEN
            INSERT INTO public.ak_global_config_translations (config_id, language_code, translated_value)
            VALUES (config_id, 'zh', zh_value)
            ON CONFLICT (config_id, language_code) DO UPDATE SET
                translated_value = EXCLUDED.translated_value,
                updated_at = NOW();
        END IF;
        
        -- 英文翻译
        IF en_value IS NOT NULL THEN
            INSERT INTO public.ak_global_config_translations (config_id, language_code, translated_value)
            VALUES (config_id, 'en', en_value)
            ON CONFLICT (config_id, language_code) DO UPDATE SET
                translated_value = EXCLUDED.translated_value,
                updated_at = NOW();
        END IF;
        
        -- 繁体中文翻译
        IF tw_value IS NOT NULL THEN
            INSERT INTO public.ak_global_config_translations (config_id, language_code, translated_value)
            VALUES (config_id, 'tw', tw_value)
            ON CONFLICT (config_id, language_code) DO UPDATE SET
                translated_value = EXCLUDED.translated_value,
                updated_at = NOW();
        END IF;
        
        -- 日文翻译
        IF ja_value IS NOT NULL THEN
            INSERT INTO public.ak_global_config_translations (config_id, language_code, translated_value)
            VALUES (config_id, 'ja', ja_value)
            ON CONFLICT (config_id, language_code) DO UPDATE SET
                translated_value = EXCLUDED.translated_value,
                updated_at = NOW();
        END IF;
    END IF;
    
    RAISE NOTICE '已迁移配置项: %', p_base_key;
END;
$$ LANGUAGE plpgsql;

-- 4. 执行数据迁移
DO $$
BEGIN
    RAISE NOTICE '=== 开始迁移全局配置数据 ===';
    
    -- 公司基础信息（需要翻译）
    PERFORM migrate_config_item('company_name', 'company', true, 1);
    PERFORM migrate_config_item('company_slogan', 'company', true, 2);
    PERFORM migrate_config_item('company_address', 'company', true, 3);
    
    -- 联系方式（不需要翻译）
    PERFORM migrate_config_item('company_phone', 'contact', false, 10);
    PERFORM migrate_config_item('company_email', 'contact', false, 11);
    PERFORM migrate_config_item('company_icp', 'legal', false, 12);
    
    -- 媒体资源（不需要翻译）
    PERFORM migrate_config_item('company_logo_url', 'media', false, 20);
    
    -- 社交媒体链接（不需要翻译）
    PERFORM migrate_config_item('social_wechat_url', 'social', false, 30);
    PERFORM migrate_config_item('social_weibo_url', 'social', false, 31);
    PERFORM migrate_config_item('social_qq_url', 'social', false, 32);
    PERFORM migrate_config_item('social_linkedin_url', 'social', false, 33);
    PERFORM migrate_config_item('social_twitter_url', 'social', false, 34);
    
    -- 热门搜索关键词（需要翻译）
    PERFORM migrate_config_item('hot_search_1', 'search', true, 50);
    PERFORM migrate_config_item('hot_search_2', 'search', true, 51);
    PERFORM migrate_config_item('hot_search_3', 'search', true, 52);
    PERFORM migrate_config_item('hot_search_4', 'search', true, 53);
    PERFORM migrate_config_item('hot_search_5', 'search', true, 54);
    
    RAISE NOTICE '=== 全局配置数据迁移完成 ===';
    
    -- 记录迁移成功
    INSERT INTO public.migration_log (migration_name, status, message)
    VALUES ('global_config_migration', 'completed', '全局配置数据迁移成功完成');
    
EXCEPTION WHEN OTHERS THEN
    -- 记录迁移失败
    INSERT INTO public.migration_log (migration_name, status, message)
    VALUES ('global_config_migration', 'failed', '全局配置数据迁移失败: ' || SQLERRM);
    
    RAISE;
END $$;

-- 5. 验证迁移结果
DO $$
DECLARE
    config_count INTEGER;
    translation_count INTEGER;
    missing_configs TEXT[] := ARRAY[]::TEXT[];
    config_key TEXT;
BEGIN
    RAISE NOTICE '=== 验证迁移结果 ===';
    
    -- 检查主配置表记录数
    SELECT COUNT(*) INTO config_count FROM public.ak_global_config WHERE is_active = true;
    RAISE NOTICE '主配置表记录数: %', config_count;
    
    -- 检查翻译表记录数
    SELECT COUNT(*) INTO translation_count FROM public.ak_global_config_translations WHERE is_active = true;
    RAISE NOTICE '翻译表记录数: %', translation_count;
    
    -- 检查必要的配置项是否存在
    FOR config_key IN 
        SELECT unnest(ARRAY[
            'company_name', 'company_slogan', 'company_address',
            'company_phone', 'company_email', 'company_icp',
            'company_logo_url', 'social_wechat_url', 'social_weibo_url',
            'hot_search_1', 'hot_search_2', 'hot_search_3'
        ])
    LOOP
        IF NOT EXISTS (SELECT 1 FROM public.ak_global_config WHERE config_key = config_key AND is_active = true) THEN
            missing_configs := array_append(missing_configs, config_key);
        END IF;
    END LOOP;
    
    IF array_length(missing_configs, 1) > 0 THEN
        RAISE WARNING '缺少以下配置项: %', array_to_string(missing_configs, ', ');
    ELSE
        RAISE NOTICE '所有必要配置项都已正确迁移';
    END IF;
    
    -- 显示迁移摘要
    RAISE NOTICE '=== 迁移摘要 ===';
    RAISE NOTICE '主配置记录: % 条', config_count;
    RAISE NOTICE '翻译记录: % 条', translation_count;
    RAISE NOTICE '缺少配置: % 项', COALESCE(array_length(missing_configs, 1), 0);
END $$;

-- 6. 测试查询
DO $$
DECLARE
    test_result RECORD;
BEGIN
    RAISE NOTICE '=== 测试新配置系统 ===';
    
    -- 测试中文配置查询
    SELECT config_key, config_value INTO test_result
    FROM vw_global_config_multilingual 
    WHERE config_key = 'company_name' AND language_code = 'zh'
    LIMIT 1;
    
    IF FOUND THEN
        RAISE NOTICE '中文公司名称: %', test_result.config_value;
    ELSE
        RAISE WARNING '未找到中文公司名称配置';
    END IF;
    
    -- 测试函数调用
    RAISE NOTICE '函数测试 - 英文公司名称: %', 
        (SELECT config_value FROM get_config_by_language('en') WHERE config_key = 'company_name' LIMIT 1);
    
    -- 测试热门搜索
    RAISE NOTICE '热门搜索关键词:';
    FOR test_result IN 
        SELECT search_term FROM get_hot_searches('zh') LIMIT 3
    LOOP
        RAISE NOTICE '- %', test_result.search_term;
    END LOOP;
END $$;

-- 7. 清理迁移函数
DROP FUNCTION IF EXISTS migrate_config_item(VARCHAR, VARCHAR, BOOLEAN, INTEGER);

-- 8. 创建回滚脚本（注释状态，需要时取消注释）
/*
-- 回滚脚本 - 仅在必要时使用
DO $$
BEGIN
    RAISE NOTICE '开始回滚操作...';
    
    -- 删除新表数据
    DELETE FROM public.ak_global_config_translations;
    DELETE FROM public.ak_global_config;
    
    -- 从备份恢复原有数据（如果需要）
    -- INSERT INTO public.ak_global_configs SELECT * FROM public.ak_global_configs_backup;
    
    RAISE NOTICE '回滚操作完成';
END $$;
*/

-- 9. 最终消息
DO $$
BEGIN
    RAISE NOTICE '====================================================';
    RAISE NOTICE '全局配置数据迁移脚本执行完成！';
    RAISE NOTICE '====================================================';
    RAISE NOTICE '后续步骤：';
    RAISE NOTICE '1. 检查上述验证结果';
    RAISE NOTICE '2. 测试前端应用功能';
    RAISE NOTICE '3. 确认无误后可删除备份表：DROP TABLE ak_global_configs_backup;';
    RAISE NOTICE '4. 检查迁移日志：SELECT * FROM migration_log WHERE migration_name = ''global_config_migration'';';
    RAISE NOTICE '====================================================';
END $$;
