import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { requireFrontendServiceToken } from "@/lib/api/public-auth"
import {
  HOSPITALS_PAGE_ENTITY_KEY,
  HOSPITALS_PAGE_LOCALE_CODES,
  type HospitalsPageLocaleCode,
} from "@/lib/pages/hospitals-page/locales"
import { parseHospitalsPageJsonForStorage } from "@/lib/pages/hospitals-page/validate-payload"
import type { HospitalsPageFormStateShape } from "@/lib/pages/hospitals-page/form-types"
import { normalizeHospitalsPageLocaleImagesForStorage } from "@/lib/pages/hospitals-page/shared-images"

export const dynamic = "force-dynamic"
export const revalidate = 0

const NO_CACHE_HEADERS = {
  "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate",
  Pragma: "no-cache",
  Expires: "0",
}

function rowToFormState(contentJson: unknown): HospitalsPageFormStateShape {
  let parsed: unknown = contentJson
  if (typeof contentJson === "string") {
    try {
      parsed = JSON.parse(contentJson)
    } catch {
      parsed = undefined
    }
  }
  return parseHospitalsPageJsonForStorage(parsed).data
}

export async function GET(req: NextRequest) {
  const authError = requireFrontendServiceToken(req)
  if (authError) return authError

  try {
    const hospitalsPageLocale = (prisma as unknown as {
      hospitalsPageLocale: {
        findMany(args: {
          where: { entityKey: string }
          orderBy: { locale: "asc" | "desc" }
        }): Promise<Array<{ locale: string; contentJson: unknown }>>
      }
    }).hospitalsPageLocale

    const rows = await hospitalsPageLocale.findMany({
      where: { entityKey: HOSPITALS_PAGE_ENTITY_KEY },
      orderBy: { locale: "asc" },
    })

    const locales: Partial<Record<HospitalsPageLocaleCode, HospitalsPageFormStateShape>> = {}
    for (const row of rows) {
      if (!HOSPITALS_PAGE_LOCALE_CODES.includes(row.locale as HospitalsPageLocaleCode)) continue
      locales[row.locale as HospitalsPageLocaleCode] = rowToFormState(row.contentJson)
    }

    return NextResponse.json(
      { success: true as const, locales: normalizeHospitalsPageLocaleImagesForStorage(locales) },
      { headers: NO_CACHE_HEADERS }
    )
  } catch (error) {
    console.error("[public/hospitals-page] GET error:", error)
    return NextResponse.json(
      { success: false as const, error: "Failed to load hospitals page" },
      { status: 500, headers: NO_CACHE_HEADERS }
    )
  }
}
