-- 为 tb_package_usage 新增订单号与退款快照字段
-- 目标：资产套餐接口直接读快照，不联表 tb_order/tb_refund_request
ALTER TABLE tb_package_usage
    ADD COLUMN IF NOT EXISTS order_no VARCHAR(30) NOT NULL DEFAULT '',
    ADD COLUMN IF NOT EXISTS refund_id BIGINT,
    ADD COLUMN IF NOT EXISTS refund_no VARCHAR(50) NOT NULL DEFAULT '';

COMMENT ON COLUMN tb_package_usage.order_no IS '订单号快照（从订单复制）';
COMMENT ON COLUMN tb_package_usage.refund_id IS '退款单ID快照（退款后写入）';
COMMENT ON COLUMN tb_package_usage.refund_no IS '退款单号快照（退款后写入）';

CREATE INDEX IF NOT EXISTS idx_package_usage_refund_id ON tb_package_usage(refund_id);

-- 存量数据回填订单号：通过 order_id 关联订单表
UPDATE tb_package_usage pu
SET order_no = o.order_no
FROM tb_order o
WHERE pu.order_id = o.id
  AND pu.order_id != 0
  AND (pu.order_no = '' OR pu.order_no IS NULL);

-- 存量数据回填退款快照（优先 package_usage_id 精准映射）
UPDATE tb_package_usage pu
SET refund_id = r.id,
    refund_no = r.refund_no
FROM tb_refund_request r
WHERE r.package_usage_id IS NOT NULL
  AND pu.id = r.package_usage_id
  AND (
      pu.refund_id IS NULL
      OR pu.refund_no = ''
      OR pu.refund_no IS NULL
  );

-- 兜底回填：按 order_id 取最新退款单（兼容历史未填 package_usage_id 的场景）
WITH latest_refund AS (
    SELECT DISTINCT ON (order_id) id, order_id, refund_no
    FROM tb_refund_request
    ORDER BY order_id, id DESC
)
UPDATE tb_package_usage pu
SET refund_id = lr.id,
    refund_no = lr.refund_no
FROM latest_refund lr
WHERE pu.order_id = lr.order_id
  AND pu.order_id != 0
  AND (
      pu.refund_id IS NULL
      OR pu.refund_no = ''
      OR pu.refund_no IS NULL
  );
