/*
  Warnings:

  - Enum values for "ModerationStatus" are being changed from:
      PENDING | APPROVED | REJECTED
    to:
      DRAFT | SUBMITTED | PUBLISHED | REJECTED

  This migration preserves existing data with a safe mapping:
    PENDING   -> SUBMITTED
    APPROVED  -> PUBLISHED
    REJECTED  -> REJECTED
*/

-- New enum with desired values
CREATE TYPE "ModerationStatus_new" AS ENUM ('DRAFT', 'SUBMITTED', 'PUBLISHED', 'REJECTED');

-- Add submittedAt columns
ALTER TABLE "coupons" ADD COLUMN "submittedAt" TIMESTAMP(3);
ALTER TABLE "lucky_draws" ADD COLUMN "submittedAt" TIMESTAMP(3);

-- Update coupons.moderationStatus enum type with mapping
ALTER TABLE "coupons" ALTER COLUMN "moderationStatus" DROP DEFAULT;
ALTER TABLE "coupons"
  ALTER COLUMN "moderationStatus"
  TYPE "ModerationStatus_new"
  USING (
    CASE "moderationStatus"::text
      WHEN 'PENDING' THEN 'SUBMITTED'
      WHEN 'APPROVED' THEN 'PUBLISHED'
      WHEN 'REJECTED' THEN 'REJECTED'
      ELSE 'DRAFT'
    END
  )::"ModerationStatus_new";
ALTER TABLE "coupons" ALTER COLUMN "moderationStatus" SET DEFAULT 'DRAFT';

-- Update lucky_draws.moderationStatus enum type with mapping
ALTER TABLE "lucky_draws" ALTER COLUMN "moderationStatus" DROP DEFAULT;
ALTER TABLE "lucky_draws"
  ALTER COLUMN "moderationStatus"
  TYPE "ModerationStatus_new"
  USING (
    CASE "moderationStatus"::text
      WHEN 'PENDING' THEN 'SUBMITTED'
      WHEN 'APPROVED' THEN 'PUBLISHED'
      WHEN 'REJECTED' THEN 'REJECTED'
      ELSE 'DRAFT'
    END
  )::"ModerationStatus_new";
ALTER TABLE "lucky_draws" ALTER COLUMN "moderationStatus" SET DEFAULT 'DRAFT';

-- Populate submittedAt/publishedAt for migrated rows (best-effort)
UPDATE "coupons"
SET "submittedAt" = COALESCE("submittedAt", "createdAt")
WHERE "moderationStatus" = 'SUBMITTED';

UPDATE "lucky_draws"
SET "submittedAt" = COALESCE("submittedAt", "createdAt")
WHERE "moderationStatus" = 'SUBMITTED';

UPDATE "coupons"
SET "publishedAt" = COALESCE("publishedAt", "updatedAt")
WHERE "moderationStatus" = 'PUBLISHED';

UPDATE "lucky_draws"
SET "publishedAt" = COALESCE("publishedAt", "updatedAt")
WHERE "moderationStatus" = 'PUBLISHED';

-- Replace enum type
ALTER TYPE "ModerationStatus" RENAME TO "ModerationStatus_old";
ALTER TYPE "ModerationStatus_new" RENAME TO "ModerationStatus";
DROP TYPE "ModerationStatus_old";

