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

export async function up({ db }: MigrateUpArgs): Promise<void> {
  // Add enum for mediaType
  await db.execute(sql`
    DO $$ BEGIN
      CREATE TYPE "enum_pages_blocks_card_grid_block_cards_media_type" AS ENUM('none', 'image', 'icon');
    EXCEPTION
      WHEN duplicate_object THEN null;
    END $$;
  `)

  // Add enum for iconPosition
  await db.execute(sql`
    DO $$ BEGIN
      CREATE TYPE "enum_pages_blocks_card_grid_block_cards_icon_position" AS ENUM('top', 'left');
    EXCEPTION
      WHEN duplicate_object THEN null;
    END $$;
  `)

  // Add columns to card-grid-block cards array table
  await db.execute(sql`
    ALTER TABLE "pages_blocks_card_grid_block_cards"
      ADD COLUMN IF NOT EXISTS "media_type" "enum_pages_blocks_card_grid_block_cards_media_type" DEFAULT 'none',
      ADD COLUMN IF NOT EXISTS "icon" varchar,
      ADD COLUMN IF NOT EXISTS "icon_position" "enum_pages_blocks_card_grid_block_cards_icon_position" DEFAULT 'top';
  `)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
    ALTER TABLE "pages_blocks_card_grid_block_cards"
      DROP COLUMN IF EXISTS "media_type",
      DROP COLUMN IF EXISTS "icon",
      DROP COLUMN IF EXISTS "icon_position";
  `)

  await db.execute(sql`
    DROP TYPE IF EXISTS "enum_pages_blocks_card_grid_block_cards_media_type";
  `)

  await db.execute(sql`
    DROP TYPE IF EXISTS "enum_pages_blocks_card_grid_block_cards_icon_position";
  `)
}
