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_button" (
  	"_order" integer NOT NULL,
  	"_parent_id" uuid NOT NULL,
  	"_path" text NOT NULL,
  	"id" varchar PRIMARY KEY NOT NULL,
  	"text" varchar NOT NULL,
  	"url" varchar NOT NULL,
  	"block_name" varchar
  );
  
  CREATE TABLE IF NOT EXISTS "group_blocks_button" (
  	"_order" integer NOT NULL,
  	"_parent_id" uuid NOT NULL,
  	"_path" text NOT NULL,
  	"id" varchar PRIMARY KEY NOT NULL,
  	"text" varchar NOT NULL,
  	"url" varchar NOT NULL,
  	"block_name" varchar
  );
  
  ALTER TABLE "announcement" ALTER COLUMN "date" SET DEFAULT '2025-06-15T10:51:24.116Z';
  ALTER TABLE "calendar" ALTER COLUMN "date" SET DEFAULT '2025-06-15T10:51:24.203Z';
  ALTER TABLE "classifieds" ALTER COLUMN "until" SET DEFAULT '2025-07-08T10:51:24.219Z';
  DO $$ BEGIN
   ALTER TABLE "blog_blocks_button" ADD CONSTRAINT "blog_blocks_button_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_button" ADD CONSTRAINT "group_blocks_button_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_button_order_idx" ON "blog_blocks_button" USING btree ("_order");
  CREATE INDEX IF NOT EXISTS "blog_blocks_button_parent_id_idx" ON "blog_blocks_button" USING btree ("_parent_id");
  CREATE INDEX IF NOT EXISTS "blog_blocks_button_path_idx" ON "blog_blocks_button" USING btree ("_path");
  CREATE INDEX IF NOT EXISTS "group_blocks_button_order_idx" ON "group_blocks_button" USING btree ("_order");
  CREATE INDEX IF NOT EXISTS "group_blocks_button_parent_id_idx" ON "group_blocks_button" USING btree ("_parent_id");
  CREATE INDEX IF NOT EXISTS "group_blocks_button_path_idx" ON "group_blocks_button" USING btree ("_path");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "blog_blocks_button" DISABLE ROW LEVEL SECURITY;
  ALTER TABLE "group_blocks_button" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "blog_blocks_button" CASCADE;
  DROP TABLE "group_blocks_button" CASCADE;
  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 "classifieds" ALTER COLUMN "until" SET DEFAULT '2025-04-21T12:49:18.187Z';`)
}
