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

/**
 * Migration: Add missing locations_hours_structured table
 *
 * The Locations collection has an array field for structured opening hours
 * that requires this table to store the nested data.
 */
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
  await db.execute(sql`
    CREATE TABLE IF NOT EXISTS "locations_hours_structured" (
      "id" serial PRIMARY KEY NOT NULL,
      "_order" integer NOT NULL,
      "_parent_id" integer NOT NULL REFERENCES locations(id) ON DELETE CASCADE,
      "day" varchar,
      "closed" boolean DEFAULT false,
      "open" varchar,
      "close" varchar,
      "break_has_break" boolean DEFAULT false,
      "break_start" varchar,
      "break_end" varchar
    );

    CREATE INDEX IF NOT EXISTS "locations_hours_structured_order_idx"
      ON "locations_hours_structured" USING btree ("_order");
    CREATE INDEX IF NOT EXISTS "locations_hours_structured_parent_idx"
      ON "locations_hours_structured" USING btree ("_parent_id");
  `)
}

export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
  await db.execute(sql`
    DROP TABLE IF EXISTS "locations_hours_structured";
  `)
}
