-- 将三个表的凭证字段从 varchar(500) 改为 jsonb 数组存储（最多5个元素）
-- 同时为代理预充值记录新增 remark 备注字段
-- 注意：旧数据可能为逗号分隔多路径，用 string_to_array 拆分为数组元素
--       USING 子句中必须显式 ::text 转换，避免 PostgreSQL 隐式将空字符串转 jsonb 报错

-- tb_order.payment_voucher_key: 空/NULL → []，非空 → 按逗号拆分为数组
ALTER TABLE tb_order
    ALTER COLUMN payment_voucher_key TYPE jsonb
        USING CASE
            WHEN payment_voucher_key IS NULL OR payment_voucher_key::text = '' THEN '[]'::jsonb
            ELSE to_jsonb(string_to_array(payment_voucher_key::text, ','))
        END;

-- tb_refund_request.refund_voucher_key: 先删除旧 varchar DEFAULT 再转类型
ALTER TABLE tb_refund_request
    ALTER COLUMN refund_voucher_key DROP DEFAULT;

ALTER TABLE tb_refund_request
    ALTER COLUMN refund_voucher_key TYPE jsonb
        USING CASE
            WHEN refund_voucher_key IS NULL OR refund_voucher_key::text = '' THEN '[]'::jsonb
            ELSE to_jsonb(string_to_array(refund_voucher_key::text, ','))
        END;

ALTER TABLE tb_refund_request
    ALTER COLUMN refund_voucher_key SET DEFAULT '[]'::jsonb;

-- tb_agent_recharge_record.payment_voucher_key: 同 tb_order
ALTER TABLE tb_agent_recharge_record
    ALTER COLUMN payment_voucher_key TYPE jsonb
        USING CASE
            WHEN payment_voucher_key IS NULL OR payment_voucher_key::text = '' THEN '[]'::jsonb
            ELSE to_jsonb(string_to_array(payment_voucher_key::text, ','))
        END;

-- tb_agent_recharge_record 新增 remark 备注字段（创建后只读，NULL 表示未填写）
ALTER TABLE tb_agent_recharge_record
    ADD COLUMN IF NOT EXISTS remark text;
