import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'

/**
 * Migration: Fix Community Role Enum
 *
 * The previous migration created community_role as varchar,
 * but Payload 3.x expects an enum type for select fields.
 */
export async function up({ db }: MigrateUpArgs): Promise<void> {
  // Step 1: Create the enum type
  await db.execute(sql`
    DO $$ BEGIN
      CREATE TYPE "enum_users_community_role" AS ENUM ('none', 'viewer', 'moderator', 'manager');
    EXCEPTION
      WHEN duplicate_object THEN null;
    END $$;
  `)

  // Step 2: Drop the default first
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" DROP DEFAULT;
  `)

  // Step 3: Alter the column to use the enum type
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" TYPE "enum_users_community_role"
      USING "community_role"::"enum_users_community_role";
  `)

  // Step 4: Set the new default value with proper type
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" SET DEFAULT 'none'::"enum_users_community_role";
  `)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  // Step 1: Drop default
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" DROP DEFAULT;
  `)

  // Step 2: Revert to varchar
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" TYPE varchar
      USING "community_role"::varchar;
  `)

  // Step 3: Set varchar default
  await db.execute(sql`
    ALTER TABLE "users"
      ALTER COLUMN "community_role" SET DEFAULT 'none';
  `)

  // Step 4: Drop enum type
  await db.execute(sql`
    DROP TYPE IF EXISTS "enum_users_community_role";
  `)
}
