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

export async function up({ db }: MigrateUpArgs): Promise<void> {
  // 1. Add tenant_id to forms
  await db.execute(sql`
    ALTER TABLE "forms"
      ADD COLUMN IF NOT EXISTS "tenant_id" integer REFERENCES tenants(id) ON DELETE SET NULL;
  `)
  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "forms_tenant_idx" ON "forms" ("tenant_id");
  `)

  // 2. Add tenant_id to form_submissions
  await db.execute(sql`
    ALTER TABLE "form_submissions"
      ADD COLUMN IF NOT EXISTS "tenant_id" integer REFERENCES tenants(id) ON DELETE SET NULL;
  `)
  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "form_submissions_tenant_idx" ON "form_submissions" ("tenant_id");
  `)

  // 3. ContactFormBlock: add form_id relationship column (replaces recipientEmail)
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block"
      ADD COLUMN IF NOT EXISTS "form_id" integer REFERENCES forms(id) ON DELETE SET NULL,
      ADD COLUMN IF NOT EXISTS "show_contact_info" boolean DEFAULT true;
  `)
  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "pages_blocks_contact_form_block_form_idx"
      ON "pages_blocks_contact_form_block" ("form_id");
  `)

  // 4. ContactFormBlock locales: add successMessage
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block_locales"
      ADD COLUMN IF NOT EXISTS "success_message" varchar;
  `)

  // 5. pages_rels: add forms_id column for the block relationship
  await db.execute(sql`
    ALTER TABLE "pages_rels"
      ADD COLUMN IF NOT EXISTS "forms_id" integer REFERENCES forms(id) ON DELETE CASCADE;
  `)
  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "pages_rels_forms_idx" ON "pages_rels" ("forms_id");
  `)

  // 6. Drop old recipientEmail column (data migrated: it was just a default 'info@porwoll.de')
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block"
      DROP COLUMN IF EXISTS "recipient_email";
  `)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  // Restore recipientEmail
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block"
      ADD COLUMN IF NOT EXISTS "recipient_email" varchar DEFAULT 'info@porwoll.de';
  `)

  // Remove new columns
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block"
      DROP COLUMN IF EXISTS "form_id",
      DROP COLUMN IF EXISTS "show_contact_info";
  `)
  await db.execute(sql`
    ALTER TABLE "pages_blocks_contact_form_block_locales"
      DROP COLUMN IF EXISTS "success_message";
  `)
  await db.execute(sql`
    ALTER TABLE "pages_rels" DROP COLUMN IF EXISTS "forms_id";
  `)
  await db.execute(sql`
    ALTER TABLE "forms" DROP COLUMN IF EXISTS "tenant_id";
  `)
  await db.execute(sql`
    ALTER TABLE "form_submissions" DROP COLUMN IF EXISTS "tenant_id";
  `)
}
