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

/**
 * Migration: Add BlogWoman collections to payload_locked_documents_rels
 *
 * The multi-tenant plugin handles the tenant_id column automatically.
 * This migration only adds the required columns to payload_locked_documents_rels
 * to prevent RSC errors when accessing these collections in the admin panel.
 */
export async function up({ db }: MigrateUpArgs): Promise<void> {
  // Add favorites_id to payload_locked_documents_rels
  await db.execute(sql`
    ALTER TABLE "payload_locked_documents_rels"
    ADD COLUMN IF NOT EXISTS "favorites_id" integer
    REFERENCES favorites(id) ON DELETE CASCADE;
  `)

  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_favorites_idx"
    ON "payload_locked_documents_rels" ("favorites_id");
  `)

  // Add series_id to payload_locked_documents_rels
  await db.execute(sql`
    ALTER TABLE "payload_locked_documents_rels"
    ADD COLUMN IF NOT EXISTS "series_id" integer
    REFERENCES series(id) ON DELETE CASCADE;
  `)

  await db.execute(sql`
    CREATE INDEX IF NOT EXISTS "payload_locked_documents_rels_series_idx"
    ON "payload_locked_documents_rels" ("series_id");
  `)
}

export async function down({ db }: MigrateDownArgs): Promise<void> {
  // Remove columns in reverse order
  await db.execute(sql`
    DROP INDEX IF EXISTS "payload_locked_documents_rels_series_idx";
  `)

  await db.execute(sql`
    ALTER TABLE "payload_locked_documents_rels"
    DROP COLUMN IF EXISTS "series_id";
  `)

  await db.execute(sql`
    DROP INDEX IF EXISTS "payload_locked_documents_rels_favorites_idx";
  `)

  await db.execute(sql`
    ALTER TABLE "payload_locked_documents_rels"
    DROP COLUMN IF EXISTS "favorites_id";
  `)
}
