-- Migration 002: Fix discount double-counting in orders
--
-- PROBLEM: The orders import was calculating discount as:
--   discount = (prod_price_reg - prod_price) * quantity   <-- "sale savings" (WRONG)
--            + prorated points discount
--            + item-level promo discounts
--
-- Since `price` in the orders table already IS the sale price (prod_price, not prod_price_reg),
-- the "sale savings" component double-counted the markdown. This resulted in inflated discounts
-- and near-zero net_revenue for products sold on sale.
--
-- Example: Product with regular_price=$30, sale_price=$15, qty=2
--   BEFORE (buggy):  discount = ($30-$15)*2 + 0 + 0 = $30.00
--                    net_revenue = $15*2 - $30 = $0.00  (WRONG!)
--   AFTER (fixed):   discount = 0 + 0 + 0 = $0.00
--                    net_revenue = $15*2 - $0 = $30.00  (CORRECT!)
--
-- FIX: This cannot be fixed with a pure SQL migration because PostgreSQL doesn't store
-- prod_price_reg. The discount column has the inflated value baked in, and we can't
-- decompose which portion was the base_discount vs actual promo discounts.
--
-- REQUIRED ACTION: Run a FULL (non-incremental) orders re-import after deploying the
-- fixed orders.js. This will recalculate all discounts using the corrected formula.
--
-- Steps:
--   1. Deploy updated orders.js (base_discount removed from discount calculation)
--   2. Run: node scripts/import/orders.js --full
--      (or trigger a full sync through whatever mechanism is used)
--   3. After re-import, run the daily snapshots rebuild to propagate corrected revenue:
--      psql -f scripts/metrics-new/backfill/rebuild_daily_snapshots.sql
--   4. Re-run metrics calculation:
--      node scripts/metrics-new/calculate-metrics-new.js
--
-- VERIFICATION: After re-import, check the previously-affected products:
SELECT
    o.pid,
    p.title,
    o.order_number,
    o.price,
    o.quantity,
    o.discount,
    (o.price * o.quantity) as gross_revenue,
    (o.price * o.quantity - o.discount) as net_revenue
FROM orders o
JOIN products p ON o.pid = p.pid
WHERE o.pid IN (624756, 614513)
ORDER BY o.date DESC
LIMIT 10;

-- Expected: discount should be 0 (or small promo amount) for regular sales,
-- and net_revenue should be close to gross_revenue.
