import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { requireFrontendServiceToken } from "@/lib/api/public-auth"
import {
  DOCTORS_PAGE_ENTITY_KEY,
  DOCTORS_PAGE_LOCALE_CODES,
  type DoctorsPageLocaleCode,
} from "@/lib/pages/doctors/locales"
import { parseDoctorsPageJsonForStorage } from "@/lib/pages/doctors/validate-payload"
import type { DoctorsPageFormStateShape } from "@/lib/pages/doctors/form-types"

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): DoctorsPageFormStateShape {
  let parsed: unknown = contentJson
  if (typeof contentJson === "string") {
    try {
      parsed = JSON.parse(contentJson)
    } catch {
      parsed = undefined
    }
  }
  return parseDoctorsPageJsonForStorage(parsed).data
}

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

  try {
    // Work around stale TypeScript PrismaClient metadata in editor process.
    const doctorsPageLocale = (prisma as unknown as {
      doctorsPageLocale: {
        findMany(args: {
          where: { entityKey: string }
          orderBy: { locale: "asc" | "desc" }
        }): Promise<Array<{ locale: string; contentJson: unknown }>>
      }
    }).doctorsPageLocale

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

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

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