-- =============================================================================
-- 迁移：移除废弃的 dws_member_recall_index 表及 RLS 视图
-- 日期: 2026-03-20
-- 原因: RecallIndexTask 已于 2026-02-13 被 WBI+NCI 替代，但表和视图的 DDL
--       在 2026-02-19 schema 重命名（billiards_dws → dws）时残留至今。
--       表中无有效数据（ETL 任务已删除），属于孤儿对象。
-- 影响: 无下游消费者依赖此表数据（后端 recall 维度已改用 v_dws_member_winback_index）
-- 回滚: 从 git 历史恢复 DDL 定义并重建表和视图
-- =============================================================================

BEGIN;

-- 1. 删除 RLS 视图
DROP VIEW IF EXISTS app.v_dws_member_recall_index;

-- 2. 删除索引
DROP INDEX IF EXISTS dws.idx_dws_recall_display;

-- 3. 删除表（CASCADE 会自动清理约束）
DROP TABLE IF EXISTS dws.dws_member_recall_index CASCADE;

-- 4. 删除序列
DROP SEQUENCE IF EXISTS dws.dws_member_recall_index_recall_id_seq;

COMMIT;

-- =============================================================================
-- 验证
-- =============================================================================
DO $$
DECLARE
    tbl_exists BOOLEAN;
    view_exists BOOLEAN;
    seq_exists BOOLEAN;
BEGIN
    SELECT EXISTS(
        SELECT 1 FROM information_schema.tables
        WHERE table_schema = 'dws' AND table_name = 'dws_member_recall_index'
    ) INTO tbl_exists;

    SELECT EXISTS(
        SELECT 1 FROM information_schema.views
        WHERE table_schema = 'app' AND table_name = 'v_dws_member_recall_index'
    ) INTO view_exists;

    SELECT EXISTS(
        SELECT 1 FROM information_schema.sequences
        WHERE sequence_schema = 'dws' AND sequence_name = 'dws_member_recall_index_recall_id_seq'
    ) INTO seq_exists;

    RAISE NOTICE '表存在: % (应为 false)', tbl_exists;
    RAISE NOTICE '视图存在: % (应为 false)', view_exists;
    RAISE NOTICE '序列存在: % (应为 false)', seq_exists;

    IF tbl_exists OR view_exists OR seq_exists THEN
        RAISE EXCEPTION '清理不完整，仍有残留对象';
    END IF;
END $$;
