import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { requireFrontendServiceToken } from "@/lib/api/public-auth"
import {
  ABOUT_US_PAGE_ENTITY_KEY,
  ABOUT_US_PAGE_LOCALE_CODES,
  type AboutUsPageLocaleCode,
} from "@/lib/pages/about-us/locales"
import { parseAboutUsPageJsonForStorage } from "@/lib/pages/about-us/validate-payload"
import type { AboutUsPageFormStateShape } from "@/lib/pages/about-us/form-types"
import { normalizeAboutUsLocaleImagesForStorage } from "@/lib/pages/about-us/hero-fallback"

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): AboutUsPageFormStateShape {
  let parsed: unknown = contentJson
  if (typeof contentJson === "string") {
    try {
      parsed = JSON.parse(contentJson)
    } catch {
      parsed = undefined
    }
  }
  return parseAboutUsPageJsonForStorage(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 aboutUsPageLocale = (prisma as unknown as {
      aboutUsPageLocale: {
        findMany(args: {
          where: { entityKey: string }
          orderBy: { locale: "asc" | "desc" }
        }): Promise<Array<{ locale: string; contentJson: unknown }>>
      }
    }).aboutUsPageLocale

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

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

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