-- Migration: 0067_drop_legacy_deal_cols
-- Phase B (contract): drop legacy price/quantity columns from `deals`,
-- drop `deal_id` from `cart_items`, swap cart_items unique constraint
-- from (user_id, deal_id) to (user_id, deal_sku_id).
--
-- Pre-conditions (must be true before running):
--   1. Migration 0066 has been applied (deal_skus populated, cache cols set).
--   2. All code reads have been migrated to deal_skus / cache cols (Wave 16).
--   3. cart_items.deal_sku_id IS NOT NULL for all rows (backfill done in 0066).
--   4. No code writes original_price/discounted_price/etc. to deals table.

--> statement-breakpoint
-- 1. Drop legacy price/quantity columns from deals
ALTER TABLE "deals"
  DROP COLUMN "original_price",
  DROP COLUMN "discount_percent",
  DROP COLUMN "discounted_price",
  DROP COLUMN "quantity_total",
  DROP COLUMN "quantity_sold";

--> statement-breakpoint
-- 2. Drop the old (user_id, deal_id) unique constraint on cart_items
--    (constraint name set in initial schema; drop before removing the column)
ALTER TABLE "cart_items"
  DROP CONSTRAINT IF EXISTS "cart_items_user_id_deal_id_unique";

--> statement-breakpoint
-- 3. Set deal_sku_id NOT NULL (all rows were backfilled in 0066)
ALTER TABLE "cart_items"
  ALTER COLUMN "deal_sku_id" SET NOT NULL;

--> statement-breakpoint
-- 4. Add new unique constraint on (user_id, deal_sku_id)
ALTER TABLE "cart_items"
  ADD CONSTRAINT "cart_items_user_id_deal_sku_id_unique" UNIQUE ("user_id", "deal_sku_id");

--> statement-breakpoint
-- 5. Drop the legacy deal_id column from cart_items
ALTER TABLE "cart_items"
  DROP COLUMN "deal_id";

--> statement-breakpoint
-- 6. Drop the check constraint that referenced discount_percent on deals
--    (already removed from schema.ts; constraint may or may not exist depending
--    on whether DB was ever migrated with it applied)
ALTER TABLE "deals"
  DROP CONSTRAINT IF EXISTS "deals_discount_percent_range";
