-- Migration: backfill DRAFT deals into deal_drafts, then remove from deals
-- Idempotent: ON CONFLICT DO NOTHING on the temp-keyed insert is not possible
-- (deal_drafts has no unique constraint on source deal id), so we guard with
-- a NOT EXISTS check scoped to the same vendor+title+created_at fingerprint.
-- Safe to re-run: re-running after DELETE is a no-op (no DRAFT rows remain).

BEGIN;

INSERT INTO deal_drafts (vendor_id, payload, title, created_at, updated_at)
SELECT
  vendor_id,
  jsonb_build_object(
    'dealType',              deal_type,
    'title',                 title,
    'description',           description,
    'categoryId',            category_id,
    'isVoucher',             is_voucher,
    'originalPrice',         original_price,
    'discountPercent',       discount_percent,
    'discountedPrice',       discounted_price,
    'quantityTotal',         quantity_total,
    'windowStart',           window_start,
    'windowEnd',             window_end,
    'pickupStart',           pickup_start,
    'pickupEnd',             pickup_end,
    'pickupAddress',         pickup_address,
    'specialInstructions',   special_instructions,
    'isPersonalDeal',        is_personal_deal,
    'personalDealForUserId', personal_deal_for_user_id,
    'maxPerUser',            max_per_user
  ) AS payload,
  title,
  created_at,
  created_at  -- deals has no updated_at; use created_at for both
FROM deals
WHERE deal_state = 'DRAFT';

DELETE FROM deals WHERE deal_state = 'DRAFT';

COMMIT;
