-- 为员工线下代充值关联唯一通用审批实例。
ALTER TABLE tb_agent_recharge_record
    ADD COLUMN IF NOT EXISTS approval_instance_id bigint;

CREATE UNIQUE INDEX IF NOT EXISTS uq_agent_recharge_approval_instance
    ON tb_agent_recharge_record (approval_instance_id)
    WHERE approval_instance_id IS NOT NULL;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM pg_constraint WHERE conname = 'chk_agent_recharge_approval_instance'
    ) THEN
        ALTER TABLE tb_agent_recharge_record
            ADD CONSTRAINT chk_agent_recharge_approval_instance
            CHECK (approval_instance_id IS NULL OR approval_instance_id > 0);
    END IF;
END $$;

COMMENT ON COLUMN tb_agent_recharge_record.approval_instance_id IS '员工线下代充值关联的唯一通用审批实例 ID，在线充值为空';
