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

/**
 * Migration: Add Token Notification Fields
 *
 * Adds:
 * 1. New notification types for token management
 * 2. relatedAccount field for social account relationship
 */
export async function up({ db }: MigrateUpArgs): Promise<void> {
  // Add new enum values to yt_notifications type enum
  await db.execute(sql`
    ALTER TYPE "enum_yt_notifications_type" ADD VALUE IF NOT EXISTS 'token_expiring';
  `)
  await db.execute(sql`
    ALTER TYPE "enum_yt_notifications_type" ADD VALUE IF NOT EXISTS 'token_expired';
  `)
  await db.execute(sql`
    ALTER TYPE "enum_yt_notifications_type" ADD VALUE IF NOT EXISTS 'token_refresh_failed';
  `)
  await db.execute(sql`
    ALTER TYPE "enum_yt_notifications_type" ADD VALUE IF NOT EXISTS 'token_refreshed';
  `)

  // Add relatedAccount field to yt_notifications
  await db.execute(sql`
    ALTER TABLE "yt_notifications"
    ADD COLUMN IF NOT EXISTS "related_account_id" integer
    REFERENCES social_accounts(id) ON DELETE SET NULL;
  `)

  // Create index for the new relationship
  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "yt_notifications_related_account_idx"
    ON "yt_notifications" ("related_account_id");
  `)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  // Drop the index
  await db.execute(sql`
    DROP INDEX IF EXISTS "yt_notifications_related_account_idx";
  `)

  // Remove the relatedAccount column
  await db.execute(sql`
    ALTER TABLE "yt_notifications"
    DROP COLUMN IF EXISTS "related_account_id";
  `)

  // Note: PostgreSQL doesn't support removing enum values easily
  // The enum values will remain but won't cause issues
}
