-- Backfill users.cashiPoints from persisted sales + claimed coupon costs
-- cashiPoints balance = SUM(sales.cashiPointsEarned) - SUM(coupons.cashiPointsCost claimed)
-- Note: Claiming a coupon decrements user.cashiPoints; this migration makes historical balances consistent.

UPDATE "users" u
SET "cashiPoints" = GREATEST(
  0,
  COALESCE(
    (
      SELECT SUM(s."cashiPointsEarned")
      FROM "sales" s
      WHERE s."customerId" = u."id"
        AND s."status" = 'COMPLETED'
    ),
    0
  )
  -
  COALESCE(
    (
      SELECT SUM(c."cashiPointsCost")
      FROM "customer_coupons" cc
      JOIN "coupons" c ON c."id" = cc."couponId"
      WHERE cc."customerId" = u."id"
    ),
    0
  )
);

