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

export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
  await payload.db.drizzle.execute(sql`
   ALTER TABLE "contact_person" ADD COLUMN "photo_id" uuid;
  DO $$ BEGIN
   ALTER TABLE "contact_person" ADD CONSTRAINT "contact_person_photo_id_media_id_fk" FOREIGN KEY ("photo_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "contact_person_photo_idx" ON "contact_person" USING btree ("photo_id");`)
}

export async function down({ payload, req }: MigrateDownArgs): Promise<void> {
  await payload.db.drizzle.execute(sql`
   ALTER TABLE "contact_person" DROP CONSTRAINT "contact_person_photo_id_media_id_fk";
  
  DROP INDEX IF EXISTS "contact_person_photo_idx";
  ALTER TABLE "contact_person" DROP COLUMN IF EXISTS "photo_id";`)
}
