-- 切换到目标数据库
\c postgres;

DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'country') THEN
        CREATE TABLE country ( 
            id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TRIGGER update_country_updated_at
        BEFORE UPDATE ON "country"
        FOR EACH ROW
        EXECUTE FUNCTION update_data_modified_column();
        
        RAISE NOTICE 'created country table and trigger';
    ELSE
        RAISE NOTICE 'country table already exists';
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'country_name') THEN
        CREATE TABLE country_name (
            id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
            country_id UUID NOT NULL,
            name VARCHAR NOT NULL,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TRIGGER update_name_updated_at
        BEFORE UPDATE ON "country_name"
        FOR EACH ROW
        EXECUTE FUNCTION update_data_modified_column();
        
        RAISE NOTICE 'created country_name table and trigger';
    ELSE
        RAISE NOTICE 'country_name table already exists';
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'country_code') THEN
        CREATE TABLE country_code (
            id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
            country_id UUID NOT NULL,
            code VARCHAR NOT NULL,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TRIGGER update_code_updated_at
        BEFORE UPDATE ON "country_code"
        FOR EACH ROW
        EXECUTE FUNCTION update_data_modified_column();
        
        RAISE NOTICE 'created country_code table and trigger';
    ELSE
        RAISE NOTICE 'country_code table already exists';
    END IF;

    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'country_flag') THEN
        CREATE TABLE country_flag (
            id UUID DEFAULT gen_random_uuid_v7() PRIMARY KEY NOT NULL,
            country_id UUID NOT NULL,
            flag VARCHAR NOT NULL,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
        );
        CREATE TRIGGER update_flag_updated_at
        BEFORE UPDATE ON "country_flag"
        FOR EACH ROW
        EXECUTE FUNCTION update_data_modified_column();
        
        RAISE NOTICE 'created country_flag table and trigger';
    ELSE
        RAISE NOTICE 'country_flag table already exists';
    END IF;
END $$;

DO $$
DECLARE
    view_exists BOOLEAN;
BEGIN
    -- 检查视图是否已存在
    SELECT EXISTS (
        SELECT 1 FROM information_schema.views 
        WHERE table_name = 'country_info_view'
    ) INTO view_exists;

    -- 若视图存在，先删除（避免字段名冲突）
    IF view_exists THEN
        DROP VIEW country_info_view;
        RAISE NOTICE '已删除旧视图 country_info_view';
    END IF;

    -- 创建或更新视图
    CREATE OR REPLACE VIEW country_info_view AS
    SELECT 
        u.id AS country_id,
        n.name AS name,       -- 国家名称
        c.code AS code,       -- 国家代码
        f.flag AS flag        -- 国旗信息
    FROM 
        country u
    LEFT JOIN 
        country_name n ON u.id = n.country_id AND n.deleted = FALSE  -- 过滤已删除名称
    LEFT JOIN 
        country_code c ON u.id = c.country_id AND c.deleted = FALSE  -- 过滤已删除代码
    LEFT JOIN 
        country_flag f ON u.id = f.country_id AND f.deleted = FALSE  -- 左连接：允许无国旗数据
    WHERE
        u.deleted = FALSE;  -- 只查询未删除的国家

    -- 根据视图是否已存在输出不同提示
    IF view_exists THEN
        RAISE NOTICE '视图 country_info_view 已更新（删除旧视图后重建）';
    ELSE
        RAISE NOTICE '视图 country_info_view 已创建';
    END IF;
EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE '处理视图时发生错误: %', SQLERRM;
END $$;
