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"

export const dynamic = "force-dynamic"
export const revalidate = 0

type DoctorTranslationDelegate = {
  findMany: (args: {
    where: { doctorId: { in: string[] } }
    select: {
      doctorId: true
      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<{
    doctorId: string
    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[]
  }>>
}

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) {
  const authError = requireFrontendServiceToken(req)
  if (authError) return authError

  try {
    const rows = await prisma.doctor.findMany({
      where: { status: "published" },
      orderBy: { createdAt: "desc" },
      select: PUBLIC_DOCTOR_SELECT,
    })
    const doctorIds = rows.map((row) => row.id)
    const translationClient = (prisma as unknown as { doctorTranslation?: DoctorTranslationDelegate }).doctorTranslation
    const translationRows = doctorIds.length
      ? translationClient
        ? await translationClient.findMany({
          where: { doctorId: { in: doctorIds } },
          select: ({
            doctorId: true,
            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),
        })
        : []
      : []
    const byDoctorId = new Map<string, typeof translationRows>()
    for (const tr of translationRows) {
      const bucket = byDoctorId.get(tr.doctorId)
      if (bucket) bucket.push(tr)
      else byDoctorId.set(tr.doctorId, [tr])
    }

    return NextResponse.json(
      {
        success: true as const,
        // include the original id so frontend can use these rows in admin UI
        doctors: rows.map((row) => ({ id: row.id, ...mapToPublicDoctor(row, byDoctorId.get(row.id) ?? []) })),
      },
      { headers: NO_CACHE_HEADERS }
    )
  } catch (error) {
    console.error("[public/doctors] GET error:", error)
    return NextResponse.json(
      { success: false as const, error: "Failed to load doctors" },
      { status: 500 }
    )
  }
}
