import { NextRequest, NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { requireFrontendServiceToken } from "@/lib/api/public-auth"
import { mapToPublicDoctor, PUBLIC_DOCTOR_SELECT } from "@/lib/api/public-doctor"

type RouteContext = { params: Promise<{ slug: string }> }

type DoctorTranslationDelegate = {
  findMany: (args: {
    where: { doctorId: string }
    select: {
      locale: true
      name: true
      description: true
      credentials: true
      biography: true
      doctorStatement: true
      specialties: true
      beforeAfter: true
      reviews: true
      faq: true
      tags: true
      languages: true
    }
  }) => Promise<Array<{
    locale: string
    name: string | null
    description: string | null
    credentials: unknown
    biography: string | null
    doctorStatement: string | null
    specialties: unknown
    beforeAfter: unknown
    reviews: unknown
    faq: unknown
    tags: string[]
    languages: string[]
  }>>
}

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",
}

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

  try {
    const { slug } = await context.params
    if (!slug) {
      return NextResponse.json({ success: false as const, error: "Missing slug" }, { status: 400 })
    }

    const doctor = await prisma.doctor.findFirst({
      where: { slug, status: "published" },
      select: PUBLIC_DOCTOR_SELECT,
    })

    if (!doctor) {
      return NextResponse.json({ success: false as const, error: "Doctor not found" }, { status: 404 })
    }
    const translationClient = (prisma as unknown as { doctorTranslation?: DoctorTranslationDelegate }).doctorTranslation
    const translationRows = translationClient
        ? await translationClient.findMany({
          where: { doctorId: doctor.id },
          select: ({
            locale: true,
            name: true,
            description: true,
            credentials: true,
            credentialsHeading: true,
            biography: true,
            biographyHeading: true,
            doctorStatement: true,
            specialties: true,
            specialtiesHeading: true,
            beforeAfter: true,
            beforeAfterHeading: true,
            reviews: true,
            reviewsHeading: true,
            faq: true,
            faqHeading: true,
            tags: true,
            languages: true,
          } as any),
        })
      : []

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