-- 为 tb_package_usage 新增购买实付金额快照字段
-- paid_amount: 购买时从订单复制的实付金额（分），nullable
-- 线下支付或企业无订单分配时为 null
ALTER TABLE tb_package_usage ADD COLUMN IF NOT EXISTS paid_amount BIGINT;

COMMENT ON COLUMN tb_package_usage.paid_amount IS '购买实付金额快照（分，从订单复制，无订单或线下支付时为null）';

-- 存量数据回填：通过 order_id 关联 tb_order 回填 actual_paid_amount
-- order_id = 0 的记录（企业无订单分配）保持 null，语义正确
UPDATE tb_package_usage pu
SET paid_amount = o.actual_paid_amount
FROM tb_order o
WHERE pu.order_id = o.id
  AND pu.order_id != 0
  AND pu.paid_amount IS NULL;
