-- 创建企业微信审批业务场景与后台模板当前映射配置。
CREATE TABLE IF NOT EXISTS tb_wecom_approval_scene (
    id bigserial PRIMARY KEY,
    business_type varchar(64) NOT NULL,
    application_id bigint NOT NULL,
    template_id varchar(128) NOT NULL,
    template_name varchar(255) NOT NULL DEFAULT '',
    control_mapping jsonb NOT NULL,
    template_snapshot jsonb NOT NULL,
    template_fingerprint char(64) NOT NULL,
    status integer NOT NULL DEFAULT 1,
    last_verified_at timestamptz NOT NULL,
    created_by bigint NOT NULL,
    updated_by bigint NOT NULL,
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uq_wecom_approval_scene_business UNIQUE (business_type),
    CONSTRAINT chk_wecom_approval_scene_business CHECK (business_type IN ('refund_approval', 'offline_recharge_approval')),
    CONSTRAINT chk_wecom_approval_scene_application CHECK (application_id > 0),
    CONSTRAINT chk_wecom_approval_scene_status CHECK (status IN (0, 1))
);

CREATE INDEX IF NOT EXISTS idx_wecom_approval_scene_application
    ON tb_wecom_approval_scene (application_id, status);

COMMENT ON TABLE tb_wecom_approval_scene IS '稳定审批业务类型到企微后台模板和控件的当前映射';
COMMENT ON COLUMN tb_wecom_approval_scene.control_mapping IS '已通过模板详情校验的业务字段、控件 ID、类型及选项 key 映射';
COMMENT ON COLUMN tb_wecom_approval_scene.template_snapshot IS '校验时读取的控件最小快照，不包含审批节点或审批人规则';
COMMENT ON COLUMN tb_wecom_approval_scene.template_fingerprint IS '模板控件最小快照 SHA-256 指纹';
