-- 入口模块菜单模板、功能清单、文档入口归属迁移脚本
-- 目标：
--   1. 入口模块用 menu_profile/features 控制左侧菜单，不再靠名称包含“合同/公文”判断。
--   2. 文档记录补 entry_module_id，后续列表、上传、统计、质量校验可以按入口模块过滤。
--   3. 二级分组增加父级内文档类型唯一约束，避免规则命中不稳定。

BEGIN;

ALTER TABLE leaudit_entry_modules
ADD COLUMN IF NOT EXISTS menu_profile VARCHAR(64) NOT NULL DEFAULT 'document_review',
ADD COLUMN IF NOT EXISTS features JSONB NOT NULL DEFAULT '[]'::jsonb;

ALTER TABLE leaudit_documents
ADD COLUMN IF NOT EXISTS entry_module_id BIGINT NULL REFERENCES leaudit_entry_modules(id);

CREATE INDEX IF NOT EXISTS idx_leaudit_entry_modules_menu_profile
ON leaudit_entry_modules(menu_profile)
WHERE deleted_at IS NULL;

CREATE INDEX IF NOT EXISTS idx_leaudit_documents_entry_module_id
ON leaudit_documents(entry_module_id);

CREATE UNIQUE INDEX IF NOT EXISTS uq_leaudit_ep_groups_parent_doc_type_active
ON leaudit_evaluation_point_groups(pid, document_type_id)
WHERE deleted_at IS NULL
  AND COALESCE(pid, 0) <> 0
  AND document_type_id IS NOT NULL;

UPDATE leaudit_entry_modules
SET
    menu_profile = CASE
        WHEN path IN ('/govdoc/audits', '/govdoc', '/govdoc-audit') THEN 'govdoc'
        WHEN path IN ('/contract-template', '/contract-template/list', '/contract-template/search') THEN 'contract'
        ELSE COALESCE(NULLIF(menu_profile, ''), 'document_review')
    END,
    features = CASE
        WHEN path IN ('/govdoc/audits', '/govdoc', '/govdoc-audit')
            THEN '["home","govdoc_audits","govdoc_upload","rule_groups"]'::jsonb
        WHEN path IN ('/contract-template', '/contract-template/list', '/contract-template/search')
            THEN '["home","documents","upload","rules","contract_template_search","contract_template_list"]'::jsonb
        WHEN features IS NULL OR features = '[]'::jsonb
            THEN '["home","documents","upload","rules","rule_groups"]'::jsonb
        ELSE features
    END
WHERE deleted_at IS NULL;

UPDATE leaudit_documents d
SET entry_module_id = COALESCE(g.entry_module_id, parent.entry_module_id, dt.entry_module_id)
FROM leaudit_document_types dt
LEFT JOIN leaudit_evaluation_point_groups g ON g.id = d.group_id
LEFT JOIN leaudit_evaluation_point_groups parent ON parent.id = g.pid
WHERE d.type_id = dt.id
  AND d.entry_module_id IS NULL;

COMMIT;

-- 验证入口模块菜单字段：
-- SELECT id, name, path, menu_profile, features
-- FROM leaudit_entry_modules
-- WHERE deleted_at IS NULL
-- ORDER BY sort_order, id;

-- 验证仍未回填入口模块归属的文档：
-- SELECT COUNT(*) AS documents_without_entry_module
-- FROM leaudit_documents
-- WHERE deleted_at IS NULL
--   AND entry_module_id IS NULL;
