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

export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
  await db.execute(sql`
   CREATE TABLE IF NOT EXISTS "magazine" (
  	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  	"cover_id" uuid NOT NULL,
  	"document_id" uuid NOT NULL,
  	"date" timestamp(3) with time zone 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 "announcement" ALTER COLUMN "date" SET DEFAULT '2025-08-31T09:35:59.090Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-08-31T09:35:59.222Z';
  ALTER TABLE "classifieds" ALTER COLUMN "until" SET DEFAULT '2025-09-26T09:35:59.313Z';
  ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "magazine_id" uuid;
  DO $$ BEGIN
   ALTER TABLE "magazine" ADD CONSTRAINT "magazine_cover_id_media_id_fk" FOREIGN KEY ("cover_id") REFERENCES "public"."media"("id") ON DELETE set null ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  DO $$ BEGIN
   ALTER TABLE "magazine" ADD CONSTRAINT "magazine_document_id_documents_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."documents"("id") ON DELETE set null ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "magazine_cover_idx" ON "magazine" USING btree ("cover_id");
  CREATE INDEX IF NOT EXISTS "magazine_document_idx" ON "magazine" USING btree ("document_id");
  CREATE INDEX IF NOT EXISTS "magazine_updated_at_idx" ON "magazine" USING btree ("updated_at");
  CREATE INDEX IF NOT EXISTS "magazine_created_at_idx" ON "magazine" USING btree ("created_at");
  DO $$ BEGIN
   ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_magazine_fk" FOREIGN KEY ("magazine_id") REFERENCES "public"."magazine"("id") ON DELETE cascade ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_magazine_id_idx" ON "payload_locked_documents_rels" USING btree ("magazine_id");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "magazine" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "magazine" CASCADE;
  ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_magazine_fk";
  
  DROP INDEX IF EXISTS "payload_locked_documents_rels_magazine_id_idx";
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2025-08-24T14:31:15.010Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-08-24T14:31:15.092Z';
  ALTER TABLE "classifieds" ALTER COLUMN "until" SET DEFAULT '2025-09-17T14:31:15.112Z';
  ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "magazine_id";`)
}
