-- 增加应用默认审批发起人，并创建企微审批渠道上下文。
ALTER TABLE tb_wecom_application
    ADD COLUMN IF NOT EXISTS default_creator_userid varchar(64) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS default_creator_name varchar(100) NOT NULL DEFAULT '';

CREATE TABLE IF NOT EXISTS tb_wecom_approval_context (
    id bigserial PRIMARY KEY,
    approval_instance_id bigint NOT NULL,
    application_id bigint NOT NULL,
    business_type varchar(64) NOT NULL,
    template_id varchar(128) NOT NULL,
    creator_userid varchar(64) NOT NULL,
    creator_name varchar(100) NOT NULL,
    creator_source varchar(16) NOT NULL,
    control_mapping jsonb NOT NULL,
    template_snapshot jsonb NOT NULL,
    template_fingerprint char(64) NOT NULL,
    submission_status integer NOT NULL DEFAULT 0,
    sp_no varchar(128) NOT NULL DEFAULT '',
    last_error varchar(500) NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT uq_wecom_approval_context_instance UNIQUE (approval_instance_id),
    CONSTRAINT chk_wecom_approval_context_instance CHECK (approval_instance_id > 0),
    CONSTRAINT chk_wecom_approval_context_application CHECK (application_id > 0),
    CONSTRAINT chk_wecom_approval_context_creator CHECK (length(btrim(creator_userid)) > 0),
    CONSTRAINT chk_wecom_approval_context_creator_source CHECK (creator_source IN ('bound', 'default')),
    CONSTRAINT chk_wecom_approval_context_submission_status CHECK (submission_status IN (0, 1, 2, 3, 4)),
    CONSTRAINT chk_wecom_approval_context_mapping CHECK (jsonb_typeof(control_mapping) = 'array'),
    CONSTRAINT chk_wecom_approval_context_template CHECK (jsonb_typeof(template_snapshot) = 'object')
);

CREATE UNIQUE INDEX IF NOT EXISTS uq_wecom_approval_context_sp_no
    ON tb_wecom_approval_context (sp_no) WHERE sp_no <> '';

CREATE INDEX IF NOT EXISTS idx_wecom_approval_context_recovery
    ON tb_wecom_approval_context (submission_status, updated_at, id);

COMMENT ON COLUMN tb_wecom_application.default_creator_userid IS '代理等非企微账号提交业务时使用的默认企微审批发起人 userid';
COMMENT ON COLUMN tb_wecom_application.default_creator_name IS '默认企微审批发起人姓名快照';
COMMENT ON TABLE tb_wecom_approval_context IS '通用审批实例对应的企业微信提交安全快照与提交结果';
COMMENT ON COLUMN tb_wecom_approval_context.creator_source IS '企微发起人来源：bound 系统账号绑定，default 应用默认发起人';
COMMENT ON COLUMN tb_wecom_approval_context.submission_status IS '提交状态：0待提交，1请求处理中，2已提交，3明确失败，4结果未知';
