import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { requireFrontendServiceToken } from "@/lib/api/public-auth"
import {
  HOME_PAGE_ENTITY_KEY,
  HOME_PAGE_LOCALE_CODES,
  type HomePageLocaleCode,
} from "@/lib/pages/home/locales"
import { parseHomePageJsonForStorage } from "@/lib/pages/home/validate-payload"
import type { HomePageFormStateShape } from "@/lib/pages/home/form-types"
import { normalizeHomePageLocaleImagesForStorage } from "@/lib/pages/home/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): HomePageFormStateShape {
  // contentJson may be stored as a JSON string in the database; parse if necessary.
  let parsed: unknown = contentJson
  if (typeof contentJson === "string") {
    try {
      parsed = JSON.parse(contentJson)
    } catch {
      parsed = undefined
    }
  }
  return parseHomePageJsonForStorage(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 homePageLocale = (prisma as unknown as {
      homePageLocale: {
        findMany(args: {
          where: { entityKey: string }
          orderBy: { locale: "asc" | "desc" }
        }): Promise<Array<{ locale: string; contentJson: unknown }>>
      }
    }).homePageLocale

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

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

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