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

export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
  await db.execute(sql`
   CREATE TYPE "public"."enum_email_logs_status" AS ENUM('pending', 'sent', 'failed');
  CREATE TYPE "public"."enum_email_logs_source" AS ENUM('manual', 'form', 'system', 'newsletter');
  CREATE TABLE "email_logs" (
  	"id" serial PRIMARY KEY NOT NULL,
  	"tenant_id" integer NOT NULL,
  	"to" varchar NOT NULL,
  	"from" varchar NOT NULL,
  	"subject" varchar NOT NULL,
  	"status" "enum_email_logs_status" DEFAULT 'pending' NOT NULL,
  	"message_id" varchar,
  	"error" varchar,
  	"source" "enum_email_logs_source" DEFAULT 'manual' NOT NULL,
  	"metadata" jsonb,
  	"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
  	"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
  );
  
  ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "email_logs_id" integer;
  ALTER TABLE "email_logs" ADD CONSTRAINT "email_logs_tenant_id_tenants_id_fk" FOREIGN KEY ("tenant_id") REFERENCES "public"."tenants"("id") ON DELETE set null ON UPDATE no action;
  CREATE INDEX "email_logs_tenant_idx" ON "email_logs" USING btree ("tenant_id");
  CREATE INDEX "email_logs_updated_at_idx" ON "email_logs" USING btree ("updated_at");
  CREATE INDEX "email_logs_created_at_idx" ON "email_logs" USING btree ("created_at");
  ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_email_logs_fk" FOREIGN KEY ("email_logs_id") REFERENCES "public"."email_logs"("id") ON DELETE cascade ON UPDATE no action;
  CREATE INDEX "payload_locked_documents_rels_email_logs_id_idx" ON "payload_locked_documents_rels" USING btree ("email_logs_id");`)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
   ALTER TABLE "email_logs" DISABLE ROW LEVEL SECURITY;
  DROP TABLE "email_logs" CASCADE;
  ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_email_logs_fk";
  
  DROP INDEX "payload_locked_documents_rels_email_logs_id_idx";
  ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "email_logs_id";
  DROP TYPE "public"."enum_email_logs_status";
  DROP TYPE "public"."enum_email_logs_source";`)
}
