import { randomUUID } from "crypto"
import { NextResponse } from "next/server"
import { touchUpdatedAt } from "@/lib/content-audit"
import { Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import { getCurrentUser, isAllowedRole } from "@/lib/user"
import {
  DOCTORS_PAGE_ENTITY_KEY,
  DOCTORS_PAGE_LOCALE_CODES,
  type DoctorsPageLocaleCode,
} from "@/lib/pages/doctors/locales"
import {
  parseDoctorsPageJsonForStorage,
  parseDoctorsPagePutBody,
  type DoctorsPageSectionKey,
} from "@/lib/pages/doctors/validate-payload"
import {
  createEmptyDoctorsPageFormState,
  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",
}

async function ensureAdmin() {
  const user = await getCurrentUser()
  if (!user) {
    return { ok: false as const, res: NextResponse.json({ error: "Unauthorized" }, { status: 401, headers: NO_CACHE_HEADERS }) }
  }
  if (!isAllowedRole(user.role, ["admin"])) {
    return { ok: false as const, res: NextResponse.json({ error: "Forbidden" }, { status: 403, headers: NO_CACHE_HEADERS }) }
  }
  return { ok: true as const, user }
}

function fail(message: string, status = 400) {
  return NextResponse.json({ success: false as const, error: message }, { status, headers: NO_CACHE_HEADERS })
}

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
}

function buildMergedLocalesForSectionSave(
  existingByLocale: Partial<Record<DoctorsPageLocaleCode, DoctorsPageFormStateShape>>,
  incomingLocales: Record<string, DoctorsPageFormStateShape>,
  sectionKey: DoctorsPageSectionKey
): Record<DoctorsPageLocaleCode, DoctorsPageFormStateShape> {
  const next: Record<DoctorsPageLocaleCode, DoctorsPageFormStateShape> = {
    en: createEmptyDoctorsPageFormState(),
    tr: createEmptyDoctorsPageFormState(),
    ar: createEmptyDoctorsPageFormState(),
  }

  for (const locale of DOCTORS_PAGE_LOCALE_CODES) {
    const base = existingByLocale[locale] ?? createEmptyDoctorsPageFormState()
    const incoming = incomingLocales[locale] ?? base
    next[locale] = {
      ...base,
      [sectionKey]: incoming[sectionKey],
    }
  }

  return next
}

export async function GET() {
  const auth = await ensureAdmin()
  if (!auth.ok) return auth.res

  try {
    const rows = await prisma.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("[admin/doctors-page] GET error:", error)
    return NextResponse.json(
      { success: false as const, error: "Failed to load doctors page" },
      { status: 500, headers: NO_CACHE_HEADERS }
    )
  }
}

export async function PUT(req: Request) {
  const auth = await ensureAdmin()
  if (!auth.ok) return auth.res

  let body: unknown
  try {
    body = await req.json()
  } catch {
    return fail("Invalid JSON body")
  }

  const parsed = parseDoctorsPagePutBody(body)
  if (!parsed.ok) return fail(parsed.error)

  try {
    const existingRows = await prisma.doctorsPageLocale.findMany({
      where: { entityKey: DOCTORS_PAGE_ENTITY_KEY },
      select: { locale: true, contentJson: true },
    })

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

    const localesToPersist =
      parsed.data.sectionKey
        ? buildMergedLocalesForSectionSave(existingByLocale, parsed.data.locales, parsed.data.sectionKey)
        : (parsed.data.locales as Record<DoctorsPageLocaleCode, DoctorsPageFormStateShape>)

    const localeNow = new Date()
    const ops = (Object.entries(localesToPersist) as [DoctorsPageLocaleCode, DoctorsPageFormStateShape][]).map(
      ([locale, state]) =>
        prisma.doctorsPageLocale.upsert({
          where: {
            entityKey_locale: {
              entityKey: DOCTORS_PAGE_ENTITY_KEY,
              locale,
            },
          },
          create: {
            id: randomUUID(),
            updatedAt: localeNow,
            entityKey: DOCTORS_PAGE_ENTITY_KEY,
            locale,
            contentJson: JSON.stringify(state),
          },
          update: {
            ...touchUpdatedAt(),
            contentJson: JSON.stringify(state),
          },
        })
    )

    await prisma.$transaction(ops)
  } catch (error) {
    console.error("[admin/doctors-page] PUT error:", error)
    return NextResponse.json(
      { success: false as const, error: "Failed to save doctors page" },
      { status: 500, headers: NO_CACHE_HEADERS }
    )
  }

  return NextResponse.json({ success: true as const }, { headers: NO_CACHE_HEADERS })
}
