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 "blog_blocks_donation" (
  	"_order" integer NOT NULL,
  	"_parent_id" uuid NOT NULL,
  	"_path" text NOT NULL,
  	"id" varchar PRIMARY KEY NOT NULL,
  	"block_name" varchar
  );
  
  CREATE TABLE IF NOT EXISTS "group_blocks_donation" (
  	"_order" integer NOT NULL,
  	"_parent_id" uuid NOT NULL,
  	"_path" text NOT NULL,
  	"id" varchar PRIMARY KEY NOT NULL,
  	"block_name" varchar
  );
  
  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';
  DO $$ BEGIN
   ALTER TABLE "blog_blocks_donation" ADD CONSTRAINT "blog_blocks_donation_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."blog"("id") ON DELETE cascade ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  DO $$ BEGIN
   ALTER TABLE "group_blocks_donation" ADD CONSTRAINT "group_blocks_donation_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."group"("id") ON DELETE cascade ON UPDATE no action;
  EXCEPTION
   WHEN duplicate_object THEN null;
  END $$;
  
  CREATE INDEX IF NOT EXISTS "blog_blocks_donation_order_idx" ON "blog_blocks_donation" USING btree ("_order");
  CREATE INDEX IF NOT EXISTS "blog_blocks_donation_parent_id_idx" ON "blog_blocks_donation" USING btree ("_parent_id");
  CREATE INDEX IF NOT EXISTS "blog_blocks_donation_path_idx" ON "blog_blocks_donation" USING btree ("_path");
  CREATE INDEX IF NOT EXISTS "group_blocks_donation_order_idx" ON "group_blocks_donation" USING btree ("_order");
  CREATE INDEX IF NOT EXISTS "group_blocks_donation_parent_id_idx" ON "group_blocks_donation" USING btree ("_parent_id");
  CREATE INDEX IF NOT EXISTS "group_blocks_donation_path_idx" ON "group_blocks_donation" USING btree ("_path");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "blog_blocks_donation" DISABLE ROW LEVEL SECURITY;
  ALTER TABLE "group_blocks_donation" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "blog_blocks_donation" CASCADE;
  DROP TABLE "group_blocks_donation" CASCADE;
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2025-03-02T08:36:52.653Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-03-02T08:36:52.738Z';`)
}
