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

export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
  await db.execute(sql`
   CREATE TABLE "donation_form" (
  	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  	"photo_id" uuid NOT NULL,
  	"text" jsonb NOT NULL,
  	"url" 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 "pope_prayer_intentions" ALTER COLUMN "year" SET DEFAULT 2026;
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2026-01-11T08:54:45.107Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2026-01-11T08:54:45.188Z';
  ALTER TABLE "classifieds" ALTER COLUMN "until" SET DEFAULT '2026-02-05T08:54:45.242Z';
  ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "donation_form_id" uuid;
  ALTER TABLE "donation_form" ADD CONSTRAINT "donation_form_photo_id_media_id_fk" FOREIGN KEY ("photo_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
  CREATE INDEX "donation_form_photo_idx" ON "donation_form" USING btree ("photo_id");
  CREATE INDEX "donation_form_updated_at_idx" ON "donation_form" USING btree ("updated_at");
  CREATE INDEX "donation_form_created_at_idx" ON "donation_form" USING btree ("created_at");
  ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_donation_form_fk" FOREIGN KEY ("donation_form_id") REFERENCES "public"."donation_form"("id") ON DELETE cascade ON UPDATE no action;
  CREATE INDEX "payload_locked_documents_rels_donation_form_id_idx" ON "payload_locked_documents_rels" USING btree ("donation_form_id");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "donation_form" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "donation_form" CASCADE;
  ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_donation_form_fk";
  
  DROP INDEX "payload_locked_documents_rels_donation_form_id_idx";
  ALTER TABLE "pope_prayer_intentions" ALTER COLUMN "year" SET DEFAULT 2025;
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2025-11-23T15:05:28.806Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-11-23T15:05:28.910Z';
  ALTER TABLE "classifieds" ALTER COLUMN "until" SET DEFAULT '2025-12-18T15:05:28.976Z';
  ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "donation_form_id";`)
}
