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 "classifieds" (
  	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
  	"until" timestamp(3) with time zone DEFAULT '2025-04-21T12:49:18.187Z' NOT NULL,
  	"text" jsonb NOT NULL,
  	"email" 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 "announcement" ALTER COLUMN "date" SET DEFAULT '2025-03-23T13:49:18.078Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-03-23T13:49:18.163Z';
  ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "classifieds_id" uuid;
  CREATE INDEX IF NOT EXISTS "classifieds_updated_at_idx" ON "classifieds" USING btree ("updated_at");
  CREATE INDEX IF NOT EXISTS "classifieds_created_at_idx" ON "classifieds" USING btree ("created_at");
  DO $$ BEGIN
   ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_classifieds_fk" FOREIGN KEY ("classifieds_id") REFERENCES "public"."classifieds"("id") ON DELETE cascade ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_classifieds_id_idx" ON "payload_locked_documents_rels" USING btree ("classifieds_id");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "classifieds" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "classifieds" CASCADE;
  ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_classifieds_fk";
  
  DROP INDEX IF EXISTS "payload_locked_documents_rels_classifieds_id_idx";
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2025-03-23T10:13:37.253Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-03-23T10:13:37.343Z';
  ALTER TABLE "payload_locked_documents_rels" DROP COLUMN IF EXISTS "classifieds_id";`)
}
