-- 回滚历史价格修复
--
-- 警告：回滚会将 order_item.unit_price 恢复为成本价（旧语义），
--       将 order.total_amount 恢复为成本价合计，
--       并清除 package_usage.retail_amount。
-- 仅在确认需要回滚时执行。

BEGIN;

-- Step 1: 将 order_item 还原为旧语义
--   unit_price ← cost_price（旧成本价）
--   amount     ← 重算小计
--   cost_price ← 0（清除）
UPDATE tb_order_item
SET
    unit_price = cost_price,
    amount     = cost_price * quantity,
    cost_price = 0
WHERE cost_price > 0
  AND deleted_at IS NULL;

-- Step 2: 将 order.total_amount 恢复为成本价合计
UPDATE tb_order o
SET total_amount = sub.old_total
FROM (
    SELECT
        oi.order_id,
        SUM(oi.unit_price * oi.quantity) AS old_total
    FROM tb_order_item oi
    WHERE oi.deleted_at IS NULL
    GROUP BY oi.order_id
) sub
WHERE o.id          = sub.order_id
  AND o.deleted_at IS NULL
  AND o.total_amount != sub.old_total;

-- Step 3: 清除 package_usage.retail_amount
UPDATE tb_package_usage
SET retail_amount = NULL
WHERE retail_amount IS NOT NULL
  AND deleted_at IS NULL;

COMMIT;
