-- 为 tb_refund_request 新增资产快照字段
-- 创建退款申请时从 tb_order 复制，避免退款列表/详情查询联表订单
ALTER TABLE tb_refund_request
    ADD COLUMN IF NOT EXISTS order_type VARCHAR(20) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS asset_identifier VARCHAR(100) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS iot_card_id BIGINT,
    ADD COLUMN IF NOT EXISTS device_id BIGINT;

COMMENT ON COLUMN tb_refund_request.order_type IS '订单类型快照（single_card/device）';
COMMENT ON COLUMN tb_refund_request.asset_identifier IS '下单时资产标识符快照（ICCID 或 VirtualNo）';
COMMENT ON COLUMN tb_refund_request.iot_card_id IS '下单时IoT卡ID快照';
COMMENT ON COLUMN tb_refund_request.device_id IS '下单时设备ID快照';

-- 存量数据回填：通过 order_id 关联 tb_order 填充资产快照字段
UPDATE tb_refund_request r
SET order_type = o.order_type,
    asset_identifier = o.asset_identifier,
    iot_card_id = o.iot_card_id,
    device_id = o.device_id
FROM tb_order o
WHERE r.order_id = o.id
  AND (
      r.order_type = ''
      OR r.asset_identifier = ''
      OR r.iot_card_id IS NULL
      OR r.device_id IS NULL
  );
