-- =========================================================
-- trade.sql 🎉
-- 无物化视图 | 超可视提示 | 可重复执行
-- PostgreSQL 17.4+ 👍
-- =========================================================

-- 1️⃣ 开始 🚀
DO $$
BEGIN
    RAISE NOTICE '🚀============ trade 部署开始 ============🚀';
END $$;

-- 2️⃣ 连接目标库
\c postgres;

-- 3️⃣ 表结构 -----------------------------------
DO $$
BEGIN
    -- trade 主表
    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'trade') THEN
        CREATE TABLE trade (
            id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
            deleted BOOLEAN NOT NULL DEFAULT FALSE,
            created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
        );
        RAISE NOTICE '1️⃣✅ trade 主表已创建';
    ELSE
        RAISE NOTICE '1️⃣⏩ trade 主表已存在，跳过';
    END IF;

    -- remark 子表
    IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'remark') THEN
        CREATE TABLE remark (
            id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
            trade_id UUID NOT NULL,
            remark 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_remark_updated_at
            BEFORE UPDATE ON remark
            FOR EACH ROW EXECUTE FUNCTION update_data_modified_column();
        RAISE NOTICE '2️⃣✅ remark 子表已创建';
    ELSE
        RAISE NOTICE '2️⃣⏩ remark 子表已存在，跳过';
    END IF;
END $$;

-- 4️⃣ 视图 ------------------------------------
DROP VIEW IF EXISTS trade_info_view;
CREATE OR REPLACE VIEW trade_info_view AS
SELECT
    t.id AS trade_id,
    r.remark AS remark
FROM trade t
LEFT JOIN remark r ON t.id = r.trade_id AND r.deleted = FALSE
WHERE t.deleted = FALSE;

RAISE NOTICE '3️⃣✅ trade_info_view 已创建/更新';

-- 5️⃣ 性能索引 ------------------------------------------------
CREATE INDEX IF NOT EXISTS idx_remark_trade_id_deleted ON remark(trade_id, deleted);

RAISE NOTICE '4️⃣✅ 全部索引已确保存在';

-- 6️⃣ 完成 🎉
DO $$
BEGIN
    RAISE NOTICE '🎉============ trade 部署完成 ============🎉';
END $$;