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

export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
  // Add new address fields (structured) and geo coordinates to site_settings
  await db.execute(sql`
    -- Add contact_fax field
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "contact_fax" varchar;

    -- Add structured address fields
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_street" varchar;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_additional_line" varchar;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_zip" varchar;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_city" varchar;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_state" varchar;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "address_country" varchar DEFAULT 'Deutschland';

    -- Add geo coordinates fields
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "geo_lat" numeric;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "geo_lng" numeric;
    ALTER TABLE "site_settings" ADD COLUMN IF NOT EXISTS "geo_zoom" numeric DEFAULT 15;
  `)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  // Remove the new columns
  await db.execute(sql`
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "contact_fax";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_street";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_additional_line";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_zip";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_city";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_state";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "address_country";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "geo_lat";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "geo_lng";
    ALTER TABLE "site_settings" DROP COLUMN IF EXISTS "geo_zoom";
  `)
}
