-- 删除 leaudit_rule_type_bindings 前的检查 SQL（仅检查，不执行删除）
-- 使用方式：
--   psql ... -f scripts/创建sql/precheck_drop_legacy_rule_type_bindings.sql

\echo '=== 1. 文档类型总量 / 新旧绑定覆盖情况 ==='
WITH doc_types AS (
    SELECT id
    FROM leaudit_document_types
    WHERE deleted_at IS NULL
),
new_bindings AS (
    SELECT DISTINCT child.document_type_id
    FROM leaudit_evaluation_point_groups child
    JOIN leaudit_rule_group_bindings rgb
      ON rgb.group_id = child.id
     AND rgb.deleted_at IS NULL
     AND rgb.is_active = TRUE
    WHERE child.deleted_at IS NULL
      AND COALESCE(child.pid, 0) <> 0
      AND child.document_type_id IS NOT NULL
),
legacy_bindings AS (
    SELECT DISTINCT doc_type_id
    FROM leaudit_rule_type_bindings
    WHERE deleted_at IS NULL
      AND is_active = TRUE
)
SELECT
    (SELECT COUNT(*) FROM doc_types) AS doc_types_total,
    (SELECT COUNT(*) FROM new_bindings) AS doc_types_with_new_binding,
    (SELECT COUNT(*) FROM legacy_bindings) AS doc_types_with_legacy_binding,
    (
        SELECT COUNT(*)
        FROM legacy_bindings lb
        WHERE NOT EXISTS (
            SELECT 1
            FROM new_bindings nb
            WHERE nb.document_type_id = lb.doc_type_id
        )
    ) AS doc_types_legacy_only;

\echo '=== 2. 仍可能依赖旧表的活动绑定明细 ==='
SELECT
    b.id,
    b.doc_type_id,
    b.doc_type_code,
    b.rule_set_id,
    b.binding_mode,
    b.priority,
    b.region,
    b.note
FROM leaudit_rule_type_bindings b
WHERE b.deleted_at IS NULL
  AND b.is_active = TRUE
ORDER BY b.doc_type_id ASC, b.priority DESC, b.id ASC;

\echo '=== 3. 新链路活动绑定明细 ==='
SELECT
    rgb.id AS group_binding_id,
    child.id AS child_group_id,
    child.document_type_id,
    rgb.rule_set_id,
    rgb.priority,
    rgb.is_active,
    rgb.note
FROM leaudit_rule_group_bindings rgb
JOIN leaudit_evaluation_point_groups child
  ON child.id = rgb.group_id
WHERE rgb.deleted_at IS NULL
  AND rgb.is_active = TRUE
  AND child.deleted_at IS NULL
  AND COALESCE(child.pid, 0) <> 0
ORDER BY child.document_type_id ASC, child.sort_order ASC, rgb.priority DESC, rgb.id ASC;

\echo '=== 4. 删除前必须人工确认 ==='
\echo '1) 观察期内未再出现 legacy fallback update/delete 日志'
\echo '2) doc_types_legacy_only = 0'
\echo '3) 前端/脚本/外部调用不再使用 /api/rule-sets/bindings 历史 BindingId'
