import { randomUUID } from "crypto"
import { NextRequest, NextResponse } from "next/server"
import type { Doctor_status, Prisma } from "@prisma/client"
import { prisma } from "@/lib/prisma"
import {
  buildContentAudit,
  contentAuditCreateData,
  contentAuditDoctorInclude,
  requireContentAuditActor,
} from "@/lib/content-audit"
import { parseDoctorTagsFromBody } from "@/lib/doctor-tags"
import { resolveUniqueDoctorSlug } from "@/lib/doctor-slug"
import {
  DOCTOR_LOCALES,
  buildDoctorTranslations,
  parseDoctorListFieldFromDb,
  parseDoctorLocale,
  parseDoctorPayloadTranslations,
  resolveDoctorTranslation,
  serializeDoctorListFieldForDb,
  serializeDoctorLongTextJson,
  unwrapDoctorLongTextJson,
} from "@/lib/doctor-db"
import { getPersistedMediaValidationError } from "@/lib/media-manager/validate-persisted-payload"
import { normalizePersistedMediaUrls } from "@/lib/normalize-persisted-media-urls"

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 fail(message: string, status = 400) {
  return NextResponse.json({ success: false as const, error: message }, { status })
}

function isSchemaDriftError(err: unknown): boolean {
  if (err && typeof err === "object" && "code" in err && (err as { code?: string }).code === "P2022") {
    return true
  }
  const message = err instanceof Error ? err.message : ""
  return /unknown column|createdbyid|updatedbyid/i.test(message)
}

function parseIsFeatured(value: unknown): boolean {
  if (typeof value === "boolean") return value
  if (value === "true" || value === 1) return true
  if (value === "false" || value === 0) return false
  return false
}

function parseFloatValue(value: unknown): number {
  const n = typeof value === "number" ? value : Number(value)
  return Number.isFinite(n) ? n : 0
}

function parseIntValue(value: unknown): number {
  const n = typeof value === "number" ? value : Number(value)
  if (!Number.isFinite(n)) return 0
  return Math.max(0, Math.trunc(n))
}

function parseString(value: unknown): string {
  if (typeof value !== "string") return ""
  return value.trim()
}

function parseLanguages(value: unknown): string[] {
  if (!Array.isArray(value)) return []
  const out: string[] = []
  const seen = new Set<string>()
  for (const item of value) {
    if (typeof item !== "string") continue
    const normalized = item.trim().replace(/\s+/g, " ")
    if (!normalized) continue
    const key = normalized.toLowerCase()
    if (seen.has(key)) continue
    seen.add(key)
    out.push(normalized)
  }
  return out
}

function parseStringList(value: unknown): string[] {
  if (!Array.isArray(value)) return []
  return value
    .filter((v): v is string => typeof v === "string")
    .map((v) => v.trim())
    .filter((v) => v !== "")
}

function parseCredentials(value: unknown) {
  if (!value || typeof value !== "object") {
    return {
      education: [] as string[],
      certifications: [] as string[],
      researchPublications: [] as string[],
      internationalExperience: [] as string[],
    }
  }
  const source = value as {
    education?: unknown
    certifications?: unknown
    researchPublications?: unknown
    internationalExperience?: unknown
  }
  return {
    education: parseStringList(source.education),
    certifications: parseStringList(source.certifications),
    researchPublications: parseStringList(source.researchPublications),
    internationalExperience: parseStringList(source.internationalExperience),
  }
}

function parseSpecialties(value: unknown) {
  value = unwrapDoctorLongTextJson(value)
  if (!Array.isArray(value)) return []
  return value
    .map((item) => {
      if (!item || typeof item !== "object") return null
      const source = item as { title?: unknown; description?: unknown; iconKey?: unknown; text?: unknown }
      const titleRaw = typeof source.title === "string" ? source.title : typeof source.text === "string" ? source.text : ""
      const title = titleRaw.trim()
      const iconKey = typeof source.iconKey === "string" ? source.iconKey.trim() : ""
      const description = typeof source.description === "string" ? source.description.trim() : ""
      if (!title || !iconKey || !description) return null
      return { title, description, iconKey }
    })
    .filter((item): item is { title: string; description: string; iconKey: string } => item !== null)
}

function parseCases(value: unknown) {
  value = unwrapDoctorLongTextJson(value)
  if (!Array.isArray(value)) return []
  return value
    .map((item) => {
      if (!item || typeof item !== "object") return null
      const source = item as {
        image?: unknown
        imagePublicId?: unknown
        procedureType?: unknown
        graftsLabel?: unknown
        grafts?: unknown
        monthsPostOpLabel?: unknown
        monthsPostOp?: unknown
        ageLabel?: unknown
        age?: unknown
        satisfactionLabel?: unknown
        satisfaction?: unknown
      }
      const image = parseString(source.image)
      const imagePublicId = parseString(source.imagePublicId)
      const procedureType = parseString(source.procedureType)
      if (!image || !imagePublicId) return null
      const graftsLabel = parseString(source.graftsLabel) || "Grafts"
      const grafts = parseString(source.grafts)
      const monthsPostOpLabel = parseString(source.monthsPostOpLabel) || "Months Post-Op"
      const monthsPostOp = parseString(source.monthsPostOp)
      const ageLabel = parseString(source.ageLabel) || "Age"
      const age = parseString(source.age)
      const satisfactionLabel = parseString(source.satisfactionLabel) || "Satisfaction"
      const satisfaction = parseString(source.satisfaction)
      return {
        image,
        imagePublicId,
        procedureType,
        graftsLabel,
        grafts,
        monthsPostOpLabel,
        monthsPostOp,
        ageLabel,
        age,
        satisfactionLabel,
        satisfaction,
      }
    })
    .filter((item): item is {
      image: string
      imagePublicId: string
      procedureType: string
      graftsLabel: string
      grafts: string
      monthsPostOpLabel: string
      monthsPostOp: string
      ageLabel: string
      age: string
      satisfactionLabel: string
      satisfaction: string
    } => item !== null)
}

function parseReviews(value: unknown) {
  value = unwrapDoctorLongTextJson(value)
  if (!Array.isArray(value)) return []
  return value
    .map((item) => {
      if (!item || typeof item !== "object") return null
      const source = item as {
        patientName?: unknown
        name?: unknown
        country?: unknown
        treatment?: unknown
        date?: unknown
        content?: unknown
        rating?: unknown
      }
      const patientNameRaw = typeof source.patientName === "string" ? source.patientName : typeof source.name === "string" ? source.name : ""
      const patientName = patientNameRaw.trim()
      const country = parseString(source.country)
      const treatment = parseString(source.treatment)
      const content = parseString(source.content)
      if (!patientName || !country || !treatment || !content) return null

      const dateRaw = parseString(source.date)
      const date = dateRaw ? new Date(dateRaw) : null
      const validDate = date && !Number.isNaN(date.getTime()) ? date.toISOString().slice(0, 10) : ""
      const rating =
        source.rating === "" || source.rating === null || source.rating === undefined
          ? null
          : parseFloatValue(source.rating)

      return {
        patientName,
        country,
        treatment,
        date: validDate,
        content,
        rating: rating !== null && rating > 0 ? rating : null,
      }
    })
    .filter((item): item is {
      patientName: string
      country: string
      treatment: string
      date: string
      content: string
      rating: number | null
    } => item !== null)
}

function parseFaq(value: unknown) {
  value = unwrapDoctorLongTextJson(value)
  if (!Array.isArray(value)) return []
  return value
    .map((item) => {
      if (!item || typeof item !== "object") return null
      const source = item as { question?: unknown; answer?: unknown }
      const question = parseString(source.question)
      const answer = parseString(source.answer)
      if (!question || !answer) return null
      return { question, answer }
    })
    .filter((item): item is { question: string; answer: string } => item !== null)
}

function parseCredentialsJson(value: unknown): {
  education: string[]
  certifications: string[]
  researchPublications: string[]
  internationalExperience: string[]
} {
  value = unwrapDoctorLongTextJson(value)
  if (!value || typeof value !== "object") {
    return {
      education: [],
      certifications: [],
      researchPublications: [],
      internationalExperience: [],
    }
  }
  const source = value as {
    education?: unknown
    certifications?: unknown
    researchPublications?: unknown
    internationalExperience?: unknown
  }
  return {
    education: parseStringList(source.education),
    certifications: parseStringList(source.certifications),
    researchPublications: parseStringList(source.researchPublications),
    internationalExperience: parseStringList(source.internationalExperience),
  }
}

function toDoctorResponse(doctor: any,
  localized?: ReturnType<typeof buildDoctorTranslations>["en"],
  translations?: ReturnType<typeof buildDoctorTranslations>
) {
  const baseCredentials =
    doctor.credentialsJson !== null && doctor.credentialsJson !== undefined
      ? parseCredentialsJson(doctor.credentialsJson)
      : { education: [], certifications: [], researchPublications: [], internationalExperience: [] }
  const baseSpecialties =
    doctor.specialtiesJson !== null && doctor.specialtiesJson !== undefined ? parseSpecialties(doctor.specialtiesJson) : []
  const baseBeforeAfter =
    doctor.beforeAfterJson !== null && doctor.beforeAfterJson !== undefined ? parseCases(doctor.beforeAfterJson) : []
  const baseReviews =
    doctor.reviewsJson !== null && doctor.reviewsJson !== undefined ? parseReviews(doctor.reviewsJson) : []
  const baseFaq = doctor.faqJson !== null && doctor.faqJson !== undefined ? parseFaq(doctor.faqJson) : []

  return normalizePersistedMediaUrls({
    id: doctor.id,
    name: localized?.name || doctor.name,
    slug: doctor.slug,
    categoryId: doctor.categoryId,
    category: doctor.Category ?? doctor.category ?? null,
    image: doctor.image,
    imagePublicId: doctor.imagePublicId,
    rating: doctor.rating,
    reviewCount: doctor.reviewCount,
    description: localized?.description ?? doctor.description,
    experienceYears: doctor.experienceYears,
    casesCount: doctor.casesCount,
    successRate: doctor.successRate,
    nationalities: doctor.nationalities,
    languages: localized?.languages.length ? localized.languages : parseDoctorListFieldFromDb(doctor.languages),
    tags: localized?.tags.length ? localized.tags : parseDoctorListFieldFromDb(doctor.tags),
    isFeatured: doctor.isFeatured,
    status: doctor.status,
    biography: localized?.biography ?? "",
    doctorStatement: localized?.doctorStatement ?? "",
    credentials: parseCredentials(localized?.credentials ?? baseCredentials),
    credentialsHeading: localized?.credentialsHeading ?? (doctor as any).credentialsHeadingJson ?? null,
    specialties: parseSpecialties(localized?.specialties ?? baseSpecialties),
    specialtiesHeading: localized?.specialtiesHeading ?? (doctor as any).specialtiesHeadingJson ?? null,
    beforeAfter: parseCases(localized?.beforeAfter ?? baseBeforeAfter),
    beforeAfterHeading: localized?.beforeAfterHeading ?? (doctor as any).beforeAfterHeadingJson ?? null,
    reviews: parseReviews(localized?.reviews ?? baseReviews),
    reviewsHeading: localized?.reviewsHeading ?? (doctor as any).reviewsHeadingJson ?? null,
    faq: parseFaq(localized?.faq ?? baseFaq),
    faqHeading: localized?.faqHeading ?? (doctor as any).faqHeadingJson ?? null,
    translations,
    audit: buildContentAudit(doctor),
  })
}

function toSummaryDoctor(row: {
  id: string
  name: string
  image: string
  rating: number
  reviewCount: number
  status: Doctor_status
  isFeatured: boolean
  Category?: { name: string; color: string } | null
  createdAt: Date
  updatedAt: Date
  createdBy?: { id: string; name: string | null; email: string; image: string | null } | null
  updatedBy?: { id: string; name: string | null; email: string; image: string | null } | null
}) {
  return {
    id: row.id,
    name: row.name,
    image: row.image,
    rating: row.rating,
    reviewCount: row.reviewCount,
    status: row.status,
    isFeatured: row.isFeatured,
    category: row.Category
      ? { name: row.Category.name, color: row.Category.color }
      : null,
    audit: buildContentAudit(row),
  }
}

const doctorInclude = {
  Category: { select: { id: true, name: true, slug: true, color: true } },
  ...contentAuditDoctorInclude,
} satisfies Prisma.DoctorInclude

export async function GET(req: NextRequest) {
  try {
    const locale = parseDoctorLocale(req.nextUrl.searchParams.get("locale"))
    let rows: Array<{
      id: string
      name: string
      image: string
      rating: number
      reviewCount: number
      status: Doctor_status
      isFeatured: boolean
      Category?: { id: string; name: string; color: string } | null
      createdAt: Date
      updatedAt: Date
      createdBy?: { id: string; name: string | null; email: string; image: string | null } | null
      updatedBy?: { id: string; name: string | null; email: string; image: string | null } | null
    }> = []

    try {
      rows = await prisma.doctor.findMany({
        orderBy: { updatedAt: "desc" },
        include: {
          Category: { select: { id: true, name: true, color: true } },
          ...contentAuditDoctorInclude,
        },
      })
    } catch (err) {
      if (!isSchemaDriftError(err)) {
        console.warn("[doctors] primary query failed, trying compatibility fallback:", err)
      }
      try {
        rows = await prisma.doctor.findMany({
          orderBy: { updatedAt: "desc" },
          include: {
            Category: { select: { id: true, name: true, color: true } },
          },
        })
      } catch (fallbackErr) {
        console.warn("[doctors] schema drift fallback -> raw query:", fallbackErr)
        const rawRows = await prisma.$queryRaw<Array<{
          id: string
          name: string
          image: string
          rating: number
          reviewCount: number
          status: Doctor_status
          isFeatured: number | boolean
          createdAt: Date
          updatedAt: Date
          categoryId: string | null
          categoryName: string | null
          categoryColor: string | null
        }>>`
          SELECT
            d.id,
            d.name,
            d.image,
            d.rating,
            d.reviewCount,
            d.status,
            d.isFeatured,
            d.createdAt,
            d.updatedAt,
            c.id AS categoryId,
            c.name AS categoryName,
            c.color AS categoryColor
          FROM Doctor d
          LEFT JOIN Category c ON c.id = d.categoryId
          ORDER BY d.updatedAt DESC
        `
        rows = rawRows.map((r) => ({
          id: r.id,
          name: r.name,
          image: r.image,
          rating: Number(r.rating) || 0,
          reviewCount: Number(r.reviewCount) || 0,
          status: r.status,
          isFeatured: Boolean(r.isFeatured),
          createdAt: new Date(r.createdAt),
          updatedAt: new Date(r.updatedAt),
          Category: r.categoryId
            ? { id: r.categoryId, name: r.categoryName ?? "", color: r.categoryColor ?? "" }
            : null,
        }))
      }
    }

    const doctorIds = rows.map((row) => row.id)
    const translationRows = doctorIds.length
      ? await prisma.doctorTranslation.findMany({
          where: { doctorId: { in: doctorIds }, locale },
          select: { doctorId: true, locale: true, name: true },
        })
      : []
    const nameByDoctor = new Map<string, string>()
    for (const tr of translationRows) {
      const name = parseString(tr.name)
      if (name) nameByDoctor.set(tr.doctorId, name)
    }
    return NextResponse.json(
      {
        success: true as const,
        doctors: rows.map((row) => ({
          ...toSummaryDoctor(row),
          name: nameByDoctor.get(row.id) || row.name,
        })),
      },
      { headers: NO_CACHE_HEADERS }
    )
  } catch (err) {
    console.error("[doctors] GET error:", err)
    return NextResponse.json({ success: false as const, error: "Failed to load doctors" }, { status: 500 })
  }
}

export async function POST(req: NextRequest) {
  try {
    const auth = await requireContentAuditActor()
    if (!auth.ok) return auth.response

    const body = await req.json()
    const mediaError = getPersistedMediaValidationError(body)
    if (mediaError) return fail(mediaError)

    const payload = body as Record<string, unknown>
    const translations = parseDoctorPayloadTranslations(payload)
    const status: Doctor_status = body.status === "draft" ? "draft" : "published"
    const isDraft = status === "draft"

    const categoryId = parseString(body.categoryId)
    const name = translations.en.name || parseString(body.name)
    const image = parseString(body.image)
    const imagePublicId = parseString(body.imagePublicId)
    const rating = parseFloatValue(body.rating)
    const reviewCount = parseIntValue(body.reviewCount)
    const description =
      translations.en.description ?? (typeof body.description === "string" ? body.description.trim() : "")
    const experienceYears = parseIntValue(body.experienceYears)
    const casesCount = parseString(body.casesCount)
    const successRate = parseString(body.successRate)
    const nationalities = parseString(body.nationalities)
    const languages = parseLanguages(body.languages)
    const tags = parseDoctorTagsFromBody(body.tags)
    const isFeatured = parseIsFeatured(body.isFeatured)
    const biography = typeof body.biography === "string" ? body.biography.trim() : ""
    const doctorStatement = typeof body.doctorStatement === "string" ? body.doctorStatement.trim() : ""
    const credentialSource = body.credentials && typeof body.credentials === "object"
      ? (body.credentials as {
          education?: unknown
          certifications?: unknown
          researchPublications?: unknown
          internationalExperience?: unknown
        })
      : {}
    const education = parseStringList(credentialSource.education)
    const certifications = parseStringList(credentialSource.certifications)
    const researchPublications = parseStringList(credentialSource.researchPublications)
    const internationalExperience = parseStringList(credentialSource.internationalExperience)
    const credentials = parseCredentials(body.credentials)
    const specialties = parseSpecialties(body.specialties)
    const beforeAfter = parseCases(body.beforeAfter)
    const reviews = parseReviews(body.reviews)
    const faq = parseFaq(body.faq)

    let effectiveCategoryId = categoryId
    let effectiveName = name

    if (isDraft) {
      if (!effectiveCategoryId) {
        const fallbackCategory = await prisma.category.findFirst({
          select: { id: true },
          orderBy: { createdAt: "asc" },
        })
        if (!fallbackCategory) {
          return fail("At least one category is required before saving doctor drafts")
        }
        effectiveCategoryId = fallbackCategory.id
      } else {
        const selectedCategory = await prisma.category.findUnique({
          where: { id: effectiveCategoryId },
          select: { id: true },
        })
        if (!selectedCategory) {
          const fallbackCategory = await prisma.category.findFirst({
            select: { id: true },
            orderBy: { createdAt: "asc" },
          })
          if (!fallbackCategory) {
            return fail("At least one category is required before saving doctor drafts")
          }
          effectiveCategoryId = fallbackCategory.id
        }
      }
      if (!effectiveName) {
        effectiveName = "Untitled Doctor Draft"
      }
    } else {
      if (!effectiveCategoryId) return fail("Category is required")
      if (!effectiveName) return fail("Doctor name is required")
    }

    const category = await prisma.category.findUnique({ where: { id: effectiveCategoryId }, select: { id: true } })
    if (!category) return fail("Selected category does not exist")

    if (status === "published") {
      if (!image) return fail("Doctor image is required")
      if (!imagePublicId) return fail("Doctor image public id is required")
      if (!description) return fail("Description is required")
      if (rating <= 0 || rating > 5) return fail("Rating is required and must be between 0 and 5")
      if (reviewCount <= 0) return fail("Review count is required and must be greater than 0")
      if (experienceYears <= 0) return fail("Experience (Years) is required and must be greater than 0")
      if (!casesCount) return fail("Cases Count is required")
      if (!successRate) return fail("Success Rate is required")
      if (!nationalities) return fail("Nationalities is required")
      if (languages.length === 0) return fail("At least one language is required")
      if (!education.length) return fail("Education is required")
      if (!certifications.length) return fail("Certifications is required")
      if (!researchPublications.length) return fail("Research & Publications is required")
      if (!internationalExperience.length) return fail("International Experience is required")
      if (!specialties.length) return fail("Surgical Specialties is required")
      if (!doctorStatement) return fail("Doctor Statement is required")
      if (!biography) return fail("Biography is required")
      if (!reviews.length) return fail("Patient Reviews is required")
      if (!faq.length) return fail("Frequently Asked Questions is required")
    }

    const slug = await resolveUniqueDoctorSlug(effectiveName)
    const now = new Date()

    const doctor = await prisma.doctor.create({
      data: {
        id: randomUUID(),
        categoryId: effectiveCategoryId,
        name: effectiveName,
        slug,
        image,
        imagePublicId,
        rating,
        reviewCount,
        description,
        experienceYears,
        casesCount,
        successRate,
        nationalities,
        languages: serializeDoctorListFieldForDb(languages),
        tags: serializeDoctorListFieldForDb(tags),
        isFeatured,
        status,
        // biography content is stored in doctorTranslation rows (per-locale).
        credentialsJson: serializeDoctorLongTextJson(credentials),
        credentialsHeadingJson: serializeDoctorLongTextJson(body.credentialsHeading),
        biographyHeadingJson: serializeDoctorLongTextJson(body.biographyHeading),
        specialtiesJson: serializeDoctorLongTextJson(specialties),
        specialtiesHeadingJson: serializeDoctorLongTextJson(body.specialtiesHeading),
        beforeAfterJson: serializeDoctorLongTextJson(beforeAfter),
        beforeAfterHeadingJson: serializeDoctorLongTextJson(body.beforeAfterHeading),
        reviewsJson: serializeDoctorLongTextJson(reviews),
        reviewsHeadingJson: serializeDoctorLongTextJson(body.reviewsHeading),
        faqJson: serializeDoctorLongTextJson(faq),
        faqHeadingJson: serializeDoctorLongTextJson(body.faqHeading),
        ...contentAuditCreateData(auth.user.id),
      },
      include: doctorInclude,
    })
    const translationCreateRows = DOCTOR_LOCALES
      .map((localeCode) => ({ localeCode, data: translations[localeCode] }))
      .filter(({ localeCode, data }) => {
        if (localeCode === "en") return true
        const trCredentials = parseCredentials(data.credentials)
        const trSpecialties = parseSpecialties(data.specialties)
        const trBeforeAfter = parseCases(data.beforeAfter)
        const trReviews = parseReviews(data.reviews)
        const trFaq = parseFaq(data.faq)
        return (
          !!data.name ||
          !!data.description ||
          data.biography !== null ||
          data.doctorStatement !== null ||
          trCredentials.education.length > 0 ||
          trCredentials.certifications.length > 0 ||
          trCredentials.researchPublications.length > 0 ||
          trCredentials.internationalExperience.length > 0 ||
          trSpecialties.length > 0 ||
          trBeforeAfter.length > 0 ||
          trReviews.length > 0 ||
          trFaq.length > 0 ||
          data.tags.length > 0 ||
          data.languages.length > 0
        )
      })
      .map(({ localeCode, data }) => {
        const trCredentials = parseCredentials(data.credentials)
        const trSpecialties = parseSpecialties(data.specialties)
        const trBeforeAfter = parseCases(data.beforeAfter)
        const trReviews = parseReviews(data.reviews)
        const trFaq = parseFaq(data.faq)
        return {
          id: randomUUID(),
          updatedAt: now,
          doctorId: doctor.id,
          locale: localeCode,
          name: data.name || null,
          description: data.description,
          credentials: serializeDoctorLongTextJson(trCredentials),
          credentialsHeading: serializeDoctorLongTextJson(data.credentialsHeading),
          biography: data.biography,
          biographyHeading: serializeDoctorLongTextJson(data.biographyHeading),
          doctorStatement: data.doctorStatement,
          specialties: serializeDoctorLongTextJson(trSpecialties),
          specialtiesHeading: serializeDoctorLongTextJson(data.specialtiesHeading),
          beforeAfter: serializeDoctorLongTextJson(trBeforeAfter),
          beforeAfterHeading: serializeDoctorLongTextJson(data.beforeAfterHeading),
          reviews: serializeDoctorLongTextJson(trReviews),
          reviewsHeading: serializeDoctorLongTextJson(data.reviewsHeading),
          faq: serializeDoctorLongTextJson(Array.isArray(trFaq) && trFaq.length > 0 ? trFaq : faq),
          faqHeading: serializeDoctorLongTextJson(data.faqHeading),
          tags: serializeDoctorListFieldForDb(data.tags),
          languages: serializeDoctorListFieldForDb(data.languages),
        }
      })
    if (translationCreateRows.length > 0) {
      await prisma.doctorTranslation.createMany({ data: translationCreateRows })
    }
    const savedTranslations = await prisma.doctorTranslation.findMany({
      where: { doctorId: doctor.id },
      select: {
        locale: true,
        name: true,
        description: true,
        credentials: true,
        credentialsHeading: true,
        biography: true,
        doctorStatement: true,
        specialties: true,
        specialtiesHeading: true,
        beforeAfter: true,
        beforeAfterHeading: true,
        reviews: true,
        reviewsHeading: true,
        faq: true,
        faqHeading: true,
        tags: true,
        languages: true,
      },
    })
    const responseTranslations = buildDoctorTranslations(
      {
        name: doctor.name,
        description: doctor.description,
        credentials: doctor.credentialsJson,
        credentialsHeading: doctor.credentialsHeadingJson ?? null,
        biography: null,
        doctorStatement: null,
        biographyHeading: doctor.biographyHeadingJson ?? null,
        specialties: doctor.specialtiesJson,
        specialtiesHeading: doctor.specialtiesHeadingJson ?? null,
        beforeAfter: doctor.beforeAfterJson,
        beforeAfterHeading: doctor.beforeAfterHeadingJson ?? null,
        reviews: doctor.reviewsJson,
        reviewsHeading: doctor.reviewsHeadingJson ?? null,
        faq: doctor.faqJson,
        faqHeading: doctor.faqHeadingJson ?? null,
        tags: doctor.tags,
        languages: doctor.languages,
      },
      savedTranslations
    )

    return NextResponse.json(
      {
        success: true as const,
        doctor: toDoctorResponse(doctor, responseTranslations.en, responseTranslations),
      },
      { status: 201 }
    )
  } catch (err) {
    console.error("[doctors] POST error:", err)
    return NextResponse.json({ success: false as const, error: "Internal server error" }, { status: 500 })
  }
}
