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

export async function up({ payload, req }: MigrateUpArgs): Promise<void> {
  await payload.db.drizzle.execute(sql`
   CREATE TYPE "public"."enum_pope_prayer_intentions_month" AS ENUM('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
  CREATE TABLE IF NOT EXISTS "pope_prayer_intentions" (
  	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  	"year" numeric DEFAULT 2025 NOT NULL,
  	"month" "enum_pope_prayer_intentions_month" DEFAULT '01' NOT NULL,
  	"title" varchar DEFAULT 'Für ' NOT NULL,
  	"prayer" varchar NOT NULL,
  	"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
  	"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
  );
  
  ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "pope_prayer_intentions_id" uuid;
  CREATE INDEX IF NOT EXISTS "pope_prayer_intentions_updated_at_idx" ON "pope_prayer_intentions" USING btree ("updated_at");
  CREATE INDEX IF NOT EXISTS "pope_prayer_intentions_created_at_idx" ON "pope_prayer_intentions" USING btree ("created_at");
  DO $$ BEGIN
   ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_pope_prayer_intentions_fk" FOREIGN KEY ("pope_prayer_intentions_id") REFERENCES "public"."pope_prayer_intentions"("id") ON DELETE cascade ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_pope_prayer_intentions_id_idx" ON "payload_locked_documents_rels" USING btree ("pope_prayer_intentions_id");`)
}

export async function down({ payload, req }: MigrateDownArgs): Promise<void> {
  await payload.db.drizzle.execute(sql`
   ALTER TABLE "pope_prayer_intentions" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "pope_prayer_intentions" CASCADE;
  ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_pope_prayer_intentions_fk";
  
  DROP INDEX IF EXISTS "payload_locked_documents_rels_pope_prayer_intentions_id_idx";
  ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "pope_prayer_intentions_id";
  DROP TYPE "public"."enum_pope_prayer_intentions_month";`)
}
