-- 已废弃：文件名保留仅为兼容历史引用，请改用：
--   scripts/创建sql/migrate_rule_groups_to_business_roots.sql
--
-- 评查点分组迁移草案（产品新口径）
-- 目标结构：
--   一级分组 = 业务大类（如：合同、卷宗、后续新增业务）
--   二级分组 = 具体业务类型（如：建设工程合同、处罚-一般程序）
--   规则集   = 挂在二级分组下
--   一级分组 = 可绑定入口模块
--
-- 注意：
-- 1. 本脚本当前仅作为迁移草案保存，尚未执行。
-- 2. 正式执行前必须先在测试库完成全量演练。
-- 3. 其中“合同 / 卷宗”的划分需要先由业务确认哪些 document_type 归属哪个一级分组。

BEGIN;

-- 0) 预留一级分组的入口模块字段。
ALTER TABLE leaudit_evaluation_point_groups
ADD COLUMN IF NOT EXISTS entry_module_id BIGINT NULL REFERENCES leaudit_entry_modules(id);

CREATE INDEX IF NOT EXISTS idx_leaudit_ep_groups_entry_module
ON leaudit_evaluation_point_groups(entry_module_id);

-- 1) 建立目标一级分组（当前先按已知口径建立“合同 / 卷宗”两个大类）。
--    后续若有新业务，只需继续插入新的一级分组即可。
WITH root_candidates AS (
    SELECT
        'biz.contract'::varchar AS code,
        '合同'::varchar AS name,
        '合同业务大类'::text AS description,
        1::bigint AS entry_module_id,
        10::int AS sort_order
    UNION ALL
    SELECT
        'biz.case'::varchar,
        '卷宗'::varchar,
        '卷宗业务大类'::text,
        2::bigint,
        20::int
),
inserted_roots AS (
    INSERT INTO leaudit_evaluation_point_groups (
        pid,
        code,
        name,
        description,
        document_type_id,
        entry_module_id,
        sort_order,
        is_enabled,
        created_at,
        updated_at
    )
    SELECT
        0,
        rc.code,
        rc.name,
        rc.description,
        NULL,
        rc.entry_module_id,
        rc.sort_order,
        TRUE,
        NOW(),
        NOW()
    FROM root_candidates rc
    WHERE NOT EXISTS (
        SELECT 1
        FROM leaudit_evaluation_point_groups g
        WHERE g.deleted_at IS NULL
          AND COALESCE(g.pid, 0) = 0
          AND LOWER(g.code) = LOWER(rc.code)
    )
    RETURNING id, code, name
)
SELECT COUNT(*) AS inserted_root_count FROM inserted_roots;

-- 2) 建立 document_type -> 一级分组 的映射。
--    这里先按入口模块粗分：
--      合同管理 -> 合同
--      案卷智能评查 -> 卷宗
--    后续若出现其他入口，需在这里继续补 mapping。
WITH root_map AS (
    SELECT id, code, name, entry_module_id
    FROM leaudit_evaluation_point_groups
    WHERE deleted_at IS NULL
      AND COALESCE(pid, 0) = 0
      AND code IN ('biz.contract', 'biz.case')
),
doc_type_root_mapping AS (
    SELECT
        dt.id AS document_type_id,
        dt.code AS document_type_code,
        dt.name AS document_type_name,
        dt.entry_module_id,
        CASE
            WHEN dt.entry_module_id = 1 THEN (SELECT id FROM root_map WHERE code = 'biz.contract' LIMIT 1)
            WHEN dt.entry_module_id = 2 THEN (SELECT id FROM root_map WHERE code = 'biz.case' LIMIT 1)
            ELSE NULL
        END AS root_group_id
    FROM leaudit_document_types dt
    WHERE dt.deleted_at IS NULL
)
SELECT *
FROM doc_type_root_mapping
ORDER BY document_type_id;

-- 3) 为每个 document_type 建立新的二级分组（挂到一级分组下）。
WITH doc_type_root_mapping AS (
    SELECT
        dt.id AS document_type_id,
        dt.code AS document_type_code,
        dt.name AS document_type_name,
        dt.description,
        dt.entry_module_id,
        dt.sort_order,
        dt.is_enabled,
        CASE
            WHEN dt.entry_module_id = 1 THEN (
                SELECT id FROM leaudit_evaluation_point_groups
                WHERE deleted_at IS NULL AND COALESCE(pid, 0) = 0 AND code = 'biz.contract'
                LIMIT 1
            )
            WHEN dt.entry_module_id = 2 THEN (
                SELECT id FROM leaudit_evaluation_point_groups
                WHERE deleted_at IS NULL AND COALESCE(pid, 0) = 0 AND code = 'biz.case'
                LIMIT 1
            )
            ELSE NULL
        END AS root_group_id
    FROM leaudit_document_types dt
    WHERE dt.deleted_at IS NULL
),
inserted_children AS (
    INSERT INTO leaudit_evaluation_point_groups (
        pid,
        code,
        name,
        description,
        document_type_id,
        entry_module_id,
        sort_order,
        is_enabled,
        created_at,
        updated_at
    )
    SELECT
        m.root_group_id,
        m.document_type_code,
        m.document_type_name,
        COALESCE(m.description, m.document_type_name || '二级分组'),
        m.document_type_id,
        NULL,
        COALESCE(m.sort_order, 0),
        COALESCE(m.is_enabled, TRUE),
        NOW(),
        NOW()
    FROM doc_type_root_mapping m
    WHERE m.root_group_id IS NOT NULL
      AND NOT EXISTS (
          SELECT 1
          FROM leaudit_evaluation_point_groups g
          WHERE g.deleted_at IS NULL
            AND COALESCE(g.pid, 0) <> 0
            AND g.document_type_id = m.document_type_id
      )
    RETURNING id, pid, document_type_id, code, name
)
SELECT COUNT(*) AS inserted_child_count FROM inserted_children;

-- 4) 将旧“一级=具体文档类型”的规则绑定迁到新二级分组。
--    迁移策略：
--    - 若旧一级或其唯一默认子级已绑定规则集，则全部搬到新的二级分组上
--    - 旧数据本身不立刻硬删除，先留待人工复核
WITH old_doc_type_roots AS (
    SELECT
        g.id AS old_group_id,
        g.document_type_id
    FROM leaudit_evaluation_point_groups g
    WHERE g.deleted_at IS NULL
      AND COALESCE(g.pid, 0) = 0
      AND g.document_type_id IS NOT NULL
),
new_children AS (
    SELECT
        g.id AS new_group_id,
        g.document_type_id
    FROM leaudit_evaluation_point_groups g
    WHERE g.deleted_at IS NULL
      AND COALESCE(g.pid, 0) <> 0
      AND g.document_type_id IS NOT NULL
),
move_pairs AS (
    SELECT
        old.old_group_id,
        child.new_group_id,
        old.document_type_id
    FROM old_doc_type_roots old
    JOIN new_children child
      ON child.document_type_id = old.document_type_id
),
root_binding_updates AS (
    UPDATE leaudit_rule_group_bindings rgb
    SET group_id = mp.new_group_id,
        updated_at = NOW()
    FROM move_pairs mp
    WHERE rgb.group_id = mp.old_group_id
      AND rgb.deleted_at IS NULL
    RETURNING rgb.id
)
SELECT COUNT(*) AS moved_root_binding_count FROM root_binding_updates;

-- 5) 将旧默认子级（如 *.default / 通用）上的绑定也迁到新二级分组。
WITH old_default_children AS (
    SELECT
        child.id AS old_group_id,
        child.document_type_id
    FROM leaudit_evaluation_point_groups child
    JOIN leaudit_evaluation_point_groups parent
      ON parent.id = child.pid
     AND parent.deleted_at IS NULL
    WHERE child.deleted_at IS NULL
      AND COALESCE(child.pid, 0) <> 0
      AND parent.document_type_id IS NOT NULL
      AND child.document_type_id = parent.document_type_id
      AND (
          child.name = '通用'
          OR child.code LIKE '%.default'
      )
),
new_children AS (
    SELECT
        g.id AS new_group_id,
        g.document_type_id
    FROM leaudit_evaluation_point_groups g
    JOIN leaudit_evaluation_point_groups root
      ON root.id = g.pid
     AND root.deleted_at IS NULL
     AND root.document_type_id IS NULL
    WHERE g.deleted_at IS NULL
      AND COALESCE(g.pid, 0) <> 0
      AND g.document_type_id IS NOT NULL
),
move_pairs AS (
    SELECT
        old.old_group_id,
        child.new_group_id
    FROM old_default_children old
    JOIN new_children child
      ON child.document_type_id = old.document_type_id
),
default_binding_updates AS (
    UPDATE leaudit_rule_group_bindings rgb
    SET group_id = mp.new_group_id,
        updated_at = NOW()
    FROM move_pairs mp
    WHERE rgb.group_id = mp.old_group_id
      AND rgb.deleted_at IS NULL
    RETURNING rgb.id
)
SELECT COUNT(*) AS moved_default_binding_count FROM default_binding_updates;

-- 6) 重建文档类型汇总绑定，确保文档类型页仍可看到汇总规则集。
UPDATE leaudit_rule_type_bindings
SET deleted_at = NOW(),
    updated_at = NOW()
WHERE deleted_at IS NULL;

INSERT INTO leaudit_rule_type_bindings (
    doc_type_id,
    doc_type_code,
    rule_set_id,
    binding_mode,
    priority,
    is_active,
    note,
    created_at,
    updated_at,
    region
)
SELECT DISTINCT ON (c.document_type_id, rgb.rule_set_id)
    c.document_type_id,
    dt.code,
    rgb.rule_set_id,
    'explicit',
    100,
    TRUE,
    're-built from second-level group bindings after root/category migration',
    NOW(),
    NOW(),
    'default'
FROM leaudit_rule_group_bindings rgb
JOIN leaudit_evaluation_point_groups c
  ON c.id = rgb.group_id
 AND c.deleted_at IS NULL
 AND COALESCE(c.pid, 0) <> 0
JOIN leaudit_document_types dt
  ON dt.id = c.document_type_id
WHERE rgb.deleted_at IS NULL
  AND rgb.is_active = TRUE
ORDER BY c.document_type_id, rgb.rule_set_id, rgb.priority DESC, rgb.id ASC;

COMMIT;
