-- 为退款申请关联唯一通用审批实例。
ALTER TABLE tb_refund_request
    ADD COLUMN IF NOT EXISTS approval_instance_id bigint;

CREATE UNIQUE INDEX IF NOT EXISTS uq_refund_request_approval_instance
    ON tb_refund_request (approval_instance_id)
    WHERE approval_instance_id IS NOT NULL;

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

COMMENT ON COLUMN tb_refund_request.approval_instance_id IS '退款申请关联的唯一通用审批实例 ID，存量旧审批记录为空';
