import { randomUUID } from "crypto"
import { NextRequest, NextResponse } from "next/server"
import { deleteImage, deletePrefixIfEmpty, purgePrefixExcept } from "@/lib/r2-storage"
import { relocateMediaBases, rewriteMediaPathsMulti } from "@/lib/media-manager/slug-relocate"
import { normalizePersistedMediaUrls } from "@/lib/normalize-persisted-media-urls"
import { prisma } from "@/lib/prisma"
import type { Hospital_status } from "@prisma/client"
import {
  collectHospitalImagePublicIds,
  emptyHospitalLocaleFormFields,
  folderFromMediaKey,
  hospitalMediaBaseForSlug,
  HOSPITAL_LOCALES,
  HOSPITAL_SECTION_KEYS,
  normalizeHospitalSharedImages,
  sanitizePersistedHospitalSections,
} from "@/lib/hospital-db"
import { validateUrlSlug } from "@/lib/slug-validation"
import { getPersistedMediaValidationError } from "@/lib/media-manager/validate-persisted-payload"
import {
  normalizeSavePayloadMediaToCurrentBase,
  reconcileEntityMediaAfterSave,
} from "@/lib/media-manager/slug-media-reconcile"
import {
  buildContentAudit,
  contentAuditHospitalInclude,
  contentAuditUpdateData,
  touchUpdatedAt,
  requireContentAuditActor,
} from "@/lib/content-audit"

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

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

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

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

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

function parseOptionalFoundedYear(value: unknown): number | null {
  if (value === "" || value === null || value === undefined) return null
  const raw = typeof value === "string" ? value.trim() : value
  if (raw === "") return null
  const n = typeof raw === "number" ? raw : Number(raw)
  if (!Number.isFinite(n)) return null
  const y = Math.trunc(n)
  const maxY = new Date().getFullYear() + 1
  if (y < 1800 || y > maxY) return null
  return y
}

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

function parseJsonOr<T>(value: string | null | undefined, fallback: T): T {
  if (!value) return fallback
  try {
    return JSON.parse(value) as T
  } catch {
    return fallback
  }
}

function toJson(value: unknown): string {
  return JSON.stringify(value ?? {})
}

function buildLocaleSections(source: Record<string, unknown>): Record<string, unknown> {
  const out: Record<string, unknown> = {}
  for (const key of HOSPITAL_SECTION_KEYS) out[key] = source[key] ?? {}
  return out
}

function translationHospitalType(tr: Record<string, unknown> | null, row: Record<string, unknown>, locale: string): string {
  if (tr && typeof tr.hospitalType === "string" && tr.hospitalType.trim() !== "") return tr.hospitalType.trim()
  if (locale === "en") return parseString(row.type)
  return ""
}

function hasMeaningfulContent(value: unknown): boolean {
  if (value === null || value === undefined) return false
  if (typeof value === "string") return value.trim() !== ""
  if (typeof value === "number" || typeof value === "boolean") return true
  if (Array.isArray(value)) return value.some((item) => hasMeaningfulContent(item))
  if (typeof value === "object") {
    return Object.values(value as Record<string, unknown>).some((item) => hasMeaningfulContent(item))
  }
  return false
}

function buildFormFromDb(row: Record<string, unknown>, trRows: Array<Record<string, unknown>>) {
  const translations: Record<string, Record<string, unknown>> = {
    en: {},
    ar: {},
    tr: {},
  }
  for (const locale of HOSPITAL_LOCALES) {
    const tr = trRows.find((x) => x.locale === locale) ?? null
    if (!tr && locale !== "en") {
      translations[locale] = emptyHospitalLocaleFormFields()
      continue
    }
    const source = tr ?? row
    translations[locale] = {
      hospitalName:
        typeof source.name === "string" && source.name.trim() !== ""
          ? source.name
          : locale === "en"
            ? parseString(row.name)
            : "",
      hospitalLocation:
        typeof source.location === "string" && source.location.trim() !== ""
          ? source.location
          : locale === "en"
            ? parseString(row.location)
            : "",
      hospitalType: translationHospitalType(tr as Record<string, unknown> | null, row, locale),
      hero: parseJsonOr(source.heroJson as string | null | undefined, {}),
      about: parseJsonOr(source.aboutJson as string | null | undefined, {}),
      gallery: parseJsonOr(source.galleryJson as string | null | undefined, {}),
      departments: parseJsonOr(source.departmentsJson as string | null | undefined, {}),
      doctors: parseJsonOr(source.doctorsJson as string | null | undefined, {}),
      accreditation: parseJsonOr(source.accreditationJson as string | null | undefined, {}),
      technology: parseJsonOr(source.technologyJson as string | null | undefined, {}),
      visitProcess: parseJsonOr(source.visitProcessJson as string | null | undefined, {}),
      reviews: parseJsonOr(source.reviewsJson as string | null | undefined, {}),
      location: parseJsonOr(source.locationJson as string | null | undefined, {}),
      packages: parseJsonOr(source.packagesJson as string | null | undefined, {}),
      faq: parseJsonOr(source.faqJson as string | null | undefined, {}),
      cta: parseJsonOr(source.ctaJson as string | null | undefined, {}),
      similar: parseJsonOr(source.similarJson as string | null | undefined, {}),
    }
  }
  return normalizePersistedMediaUrls({
    categoryId: parseString(row.categoryId),
    isFeatured: Boolean(row.isFeatured),
    basicInfo: {
      slug: parseString(row.slug),
      image: parseString(row.image),
      imagePublicId: parseString(row.imagePublicId),
      rating: parseNumber(row.rating),
      reviewCount: Math.trunc(parseNumber(row.reviewCount)),
      badge: "",
      foundedYear:
        typeof row.foundedYear === "number" && Number.isFinite(row.foundedYear) ? row.foundedYear : "",
      bedsCount: Math.trunc(parseNonNegativeInt(row.bedsCount)),
      departmentsCount: Math.trunc(parseNonNegativeInt(row.departmentsCount)),
      doctorsCount: Math.trunc(parseNonNegativeInt(row.doctorsCount)),
      patientsPerYear: Math.trunc(parseNonNegativeInt(row.patientsPerYear)),
      isFeatured: Boolean(row.isFeatured),
    },
    translations,
  })
}

function buildHospitalImageSnapshot(row: Record<string, unknown>, trRows: Array<Record<string, unknown>>) {
  const translations = buildFormFromDb(row, trRows).translations as Record<string, unknown>
  const ids = collectHospitalImagePublicIds({
    imagePublicId: row.imagePublicId,
    translations,
  })
  const folders = new Set<string>()
  for (const id of ids) {
    const folder = folderFromMediaKey(id)
    if (folder) folders.add(folder)
  }
  return { ids, folders }
}

export async function GET(_req: NextRequest, context: RouteContext) {
  try {
    const { id } = await context.params
    if (!id) return fail("Missing id")

    let row = null as any
    try {
      row = await prisma.hospital.findUnique({
        where: { id },
        include: {
          Category: { select: { id: true, name: true, color: true } },
          ...contentAuditHospitalInclude,
        },
      })
    } catch (err) {
      console.warn("[hospitals] GET [id] primary query failed, trying compatibility fallback:", err)
      row = await prisma.hospital.findUnique({
        where: { id },
        include: {
          Category: { select: { id: true, name: true, color: true } },
        },
      })
    }
    if (!row) return fail("Hospital not found", 404)
    const trRows = await prisma.hospitalTranslation.findMany({
      where: { hospitalId: id },
      select: {
        locale: true,
        name: true,
        location: true,
        hospitalType: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })
    const form = buildFormFromDb(row as unknown as Record<string, unknown>, trRows as unknown as Array<Record<string, unknown>>)

    const { Category, ...hospitalBase } = row
    return NextResponse.json({
      success: true as const,
      hospital: {
        ...hospitalBase,
        category: Category ?? null,
        form,
        audit: buildContentAudit(row),
      },
    })
  } catch (err) {
    console.error("[hospitals] GET [id] error:", err)
    return NextResponse.json({ success: false as const, error: "Failed to load hospital" }, { status: 500 })
  }
}

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

    const { id } = await context.params
    if (!id) return fail("Missing id")
    const existing = await prisma.hospital.findUnique({
      where: { id },
      select: {
        id: true,
        categoryId: true,
        slug: true,
        imagePublicId: true,
        type: true,
        name: true,
        isFeatured: true,
        rating: true,
        reviewCount: true,
        location: true,
        status: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })
    if (!existing) return fail("Hospital not found", 404)
    const existingTranslations = await prisma.hospitalTranslation.findMany({
      where: { hospitalId: id },
      select: {
        locale: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })
    const previousSnapshot = buildHospitalImageSnapshot(
      existing as unknown as Record<string, unknown>,
      existingTranslations as unknown as Array<Record<string, unknown>>
    )

    const payload = (await req.json()) as Record<string, unknown>
    const mediaError = getPersistedMediaValidationError(payload)
    if (mediaError) return fail(mediaError)

    const status: Hospital_status = payload.status === "draft" ? "draft" : "published"
    const isDraft = status === "draft"

    const categoryId = parseString(payload.categoryId) || existing.categoryId
    let basicInfo =
      payload.basicInfo && typeof payload.basicInfo === "object"
        ? (payload.basicInfo as Record<string, unknown>)
        : {}
    let translationsInput =
      payload.translations && typeof payload.translations === "object"
        ? (payload.translations as Record<string, unknown>)
        : {}

    const slug = parseString(basicInfo.slug) || existing.slug

    const slugValidation = validateUrlSlug(slug)
    if (!slugValidation.valid) return fail(slugValidation.error ?? "Invalid slug")

    if (!isDraft) {
      if (!slug) return fail("Slug is required")
    }

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

    if (slug !== existing.slug) {
      const conflicting = await prisma.hospital.findFirst({ where: { slug, NOT: { id } }, select: { id: true } })
      if (conflicting) return fail("Slug already in use", 409)
    }

    const slugChanged = slug !== existing.slug
    const oldMediaBase = hospitalMediaBaseForSlug(existing.slug)
    const newMediaBase = hospitalMediaBaseForSlug(slug)
    if (slugChanged) {
      try {
        await relocateMediaBases([oldMediaBase], newMediaBase)
      } catch (relocateErr) {
        console.error("[hospitals] slug media relocate failed:", relocateErr)
        return fail("Failed to move hospital images for the new slug", 500)
      }
      basicInfo = rewriteMediaPathsMulti(basicInfo, [oldMediaBase], newMediaBase) as Record<string, unknown>
      translationsInput = rewriteMediaPathsMulti(
        translationsInput,
        [oldMediaBase],
        newMediaBase
      ) as Record<string, unknown>
      payload.basicInfo = basicInfo
      payload.translations = translationsInput
    } else {
      const normalizedPayload = normalizeSavePayloadMediaToCurrentBase(payload, {
        persistedOldBases: [oldMediaBase],
        currentMediaBase: newMediaBase,
      }) as Record<string, unknown>
      basicInfo =
        normalizedPayload.basicInfo && typeof normalizedPayload.basicInfo === "object"
          ? (normalizedPayload.basicInfo as Record<string, unknown>)
          : basicInfo
      translationsInput =
        normalizedPayload.translations && typeof normalizedPayload.translations === "object"
          ? (normalizedPayload.translations as Record<string, unknown>)
          : translationsInput
      payload.basicInfo = basicInfo
      payload.translations = translationsInput
    }

    let translations = normalizeHospitalSharedImages(translationsInput) as Record<string, unknown>
    let image = parseString(basicInfo.image)
    let imagePublicId = parseString(basicInfo.imagePublicId)
    const canonicalHospitalMedia = normalizePersistedMediaUrls({
      image,
      imagePublicId,
      translations,
    }) as {
      image: string
      imagePublicId: string
      translations: Record<string, unknown>
    }
    image = typeof canonicalHospitalMedia.image === "string" ? canonicalHospitalMedia.image.trim() : ""
    imagePublicId =
      typeof canonicalHospitalMedia.imagePublicId === "string"
        ? canonicalHospitalMedia.imagePublicId.trim()
        : ""
    translations = canonicalHospitalMedia.translations

    const enPayload =
      translations.en && typeof translations.en === "object" ? (translations.en as Record<string, unknown>) : {}
    const enSections = sanitizePersistedHospitalSections(
      buildLocaleSections(
        translations.en && typeof translations.en === "object" ? (translations.en as Record<string, unknown>) : {}
      )
    )

    const name = parseString(enPayload.hospitalName)
    const type = parseString(enPayload.hospitalType)
    const rating = parseNumber(basicInfo.rating)
    const reviewCount = Math.max(0, Math.trunc(parseNumber(basicInfo.reviewCount)))
    const foundedYear = parseOptionalFoundedYear(basicInfo.foundedYear)
    const bedsCount = parseNonNegativeInt(basicInfo.bedsCount)
    const departmentsCount = parseNonNegativeInt(basicInfo.departmentsCount)
    const doctorsCount = parseNonNegativeInt(basicInfo.doctorsCount)
    const patientsPerYear = parseNonNegativeInt(basicInfo.patientsPerYear)
    const isFeatured = Boolean(basicInfo.isFeatured)
    const location = parseString(enPayload.hospitalLocation)

    const updated = await prisma.hospital.update({
      where: { id },
      data: {
        categoryId,
        slug,
        name: name || "Untitled Hospital Draft",
        type,
        image,
        imagePublicId,
        rating,
        reviewCount,
        foundedYear,
        bedsCount,
        departmentsCount,
        doctorsCount,
        patientsPerYear,
        location,
        isFeatured,
        status,
        heroJson: toJson(enSections.hero),
        aboutJson: toJson(enSections.about),
        galleryJson: toJson(enSections.gallery),
        departmentsJson: toJson(enSections.departments),
        doctorsJson: toJson(enSections.doctors),
        accreditationJson: toJson(enSections.accreditation),
        technologyJson: toJson(enSections.technology),
        visitProcessJson: toJson(enSections.visitProcess),
        reviewsJson: toJson(enSections.reviews),
        locationJson: toJson(enSections.location),
        packagesJson: toJson(enSections.packages),
        faqJson: toJson(enSections.faq),
        ctaJson: toJson(enSections.cta),
        similarJson: toJson(enSections.similar),
        ...contentAuditUpdateData(auth.user.id),
      },
      include: { Category: { select: { id: true, name: true, color: true } } },
    })
    const translationNow = new Date()
    for (const locale of HOSPITAL_LOCALES) {
      const localeRawInput =
        translationsInput[locale] && typeof translationsInput[locale] === "object"
          ? (translationsInput[locale] as Record<string, unknown>)
          : {}
      const localeSectionsRaw = sanitizePersistedHospitalSections(buildLocaleSections(localeRawInput))
      const localizedNameRaw =
        typeof localeRawInput.hospitalName === "string" ? localeRawInput.hospitalName.trim() : ""
      const localizedLocationRaw =
        typeof localeRawInput.hospitalLocation === "string" ? localeRawInput.hospitalLocation.trim() : ""
      const localizedHospitalTypeRaw =
        typeof localeRawInput.hospitalType === "string" ? localeRawInput.hospitalType.trim() : ""
      if (
        locale !== "en" &&
        !hasMeaningfulContent({
          ...localeSectionsRaw,
          localizedName: localizedNameRaw,
          localizedLocation: localizedLocationRaw,
          localizedHospitalType: localizedHospitalTypeRaw,
        })
      ) {
        await prisma.hospitalTranslation.deleteMany({ where: { hospitalId: id, locale } })
        continue
      }

      const localeRaw =
        translations[locale] && typeof translations[locale] === "object"
          ? (translations[locale] as Record<string, unknown>)
          : {}
      const localeSections = sanitizePersistedHospitalSections(buildLocaleSections(localeRaw))
      const localizedName = typeof localeRaw.hospitalName === "string" ? localeRaw.hospitalName.trim() : ""
      const localizedLocation =
        typeof localeRaw.hospitalLocation === "string" ? localeRaw.hospitalLocation.trim() : ""
      const localizedHospitalType =
        typeof localeRaw.hospitalType === "string" ? localeRaw.hospitalType.trim() : ""

      await prisma.hospitalTranslation.upsert({
        where: { hospitalId_locale: { hospitalId: id, locale } },
        update: {
          ...touchUpdatedAt(),
          name: localizedName || (locale === "en" ? (name || null) : null),
          location: localizedLocation || (locale === "en" ? (location || null) : null),
          hospitalType: localizedHospitalType ? localizedHospitalType : null,
          heroJson: toJson((localeSections as Record<string, unknown>).hero ?? {}),
          aboutJson: toJson((localeSections as Record<string, unknown>).about ?? {}),
          galleryJson: toJson((localeSections as Record<string, unknown>).gallery ?? {}),
          departmentsJson: toJson((localeSections as Record<string, unknown>).departments ?? {}),
          doctorsJson: toJson((localeSections as Record<string, unknown>).doctors ?? {}),
          accreditationJson: toJson((localeSections as Record<string, unknown>).accreditation ?? {}),
          technologyJson: toJson((localeSections as Record<string, unknown>).technology ?? {}),
          visitProcessJson: toJson((localeSections as Record<string, unknown>).visitProcess ?? {}),
          reviewsJson: toJson((localeSections as Record<string, unknown>).reviews ?? {}),
          locationJson: toJson((localeSections as Record<string, unknown>).location ?? {}),
          packagesJson: toJson((localeSections as Record<string, unknown>).packages ?? {}),
          faqJson: toJson((localeSections as Record<string, unknown>).faq ?? {}),
          ctaJson: toJson((localeSections as Record<string, unknown>).cta ?? {}),
          similarJson: toJson((localeSections as Record<string, unknown>).similar ?? {}),
        },
        create: {
          id: randomUUID(),
          updatedAt: translationNow,
          hospitalId: id,
          locale,
          name: localizedName || (locale === "en" ? (name || null) : null),
          location: localizedLocation || (locale === "en" ? (location || null) : null),
          hospitalType: localizedHospitalType ? localizedHospitalType : null,
          heroJson: toJson((localeSections as Record<string, unknown>).hero ?? {}),
          aboutJson: toJson((localeSections as Record<string, unknown>).about ?? {}),
          galleryJson: toJson((localeSections as Record<string, unknown>).gallery ?? {}),
          departmentsJson: toJson((localeSections as Record<string, unknown>).departments ?? {}),
          doctorsJson: toJson((localeSections as Record<string, unknown>).doctors ?? {}),
          accreditationJson: toJson((localeSections as Record<string, unknown>).accreditation ?? {}),
          technologyJson: toJson((localeSections as Record<string, unknown>).technology ?? {}),
          visitProcessJson: toJson((localeSections as Record<string, unknown>).visitProcess ?? {}),
          reviewsJson: toJson((localeSections as Record<string, unknown>).reviews ?? {}),
          locationJson: toJson((localeSections as Record<string, unknown>).location ?? {}),
          packagesJson: toJson((localeSections as Record<string, unknown>).packages ?? {}),
          faqJson: toJson((localeSections as Record<string, unknown>).faq ?? {}),
          ctaJson: toJson((localeSections as Record<string, unknown>).cta ?? {}),
          similarJson: toJson((localeSections as Record<string, unknown>).similar ?? {}),
        },
      })
    }

    const updatedTranslations = await prisma.hospitalTranslation.findMany({
      where: { hospitalId: id },
      select: {
        locale: true,
        name: true,
        location: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })

    const nextSnapshot = buildHospitalImageSnapshot(
      updated as unknown as Record<string, unknown>,
      updatedTranslations as unknown as Array<Record<string, unknown>>
    )

    await reconcileEntityMediaAfterSave({
      namespaceChanged: slugChanged,
      oldBases: [oldMediaBase],
      newMediaBase,
      previousMediaKeys: previousSnapshot.ids,
      savedPayload: {
        imagePublicId: updated.imagePublicId,
        translations: buildFormFromDb(
          updated as unknown as Record<string, unknown>,
          updatedTranslations as unknown as Array<Record<string, unknown>>
        ).translations,
      },
      collectNextMediaKeys: collectHospitalImagePublicIds,
    })

    const auditRow = await prisma.hospital.findUnique({
      where: { id },
      select: { createdAt: true, updatedAt: true, ...contentAuditHospitalInclude },
    })

    const { Category, ...updatedBase } = updated
    return NextResponse.json({
      success: true as const,
      hospital: {
        ...updatedBase,
        category: Category ?? null,
        form: buildFormFromDb(
          updated as unknown as Record<string, unknown>,
          updatedTranslations as unknown as Array<Record<string, unknown>>
        ),
        audit: buildContentAudit(
          auditRow ?? { createdAt: updated.createdAt, updatedAt: updated.updatedAt }
        ),
      },
    })
  } catch (err) {
    console.error("[hospitals] PUT error:", err)
    return NextResponse.json({ success: false as const, error: "Failed to update hospital" }, { status: 500 })
  }
}

export async function DELETE(_req: NextRequest, context: RouteContext) {
  try {
    const { id } = await context.params
    if (!id) return fail("Missing id")
    const existing = await prisma.hospital.findUnique({
      where: { id },
      select: {
        id: true,
        imagePublicId: true,
        type: true,
        categoryId: true,
        slug: true,
        name: true,
        isFeatured: true,
        rating: true,
        reviewCount: true,
        location: true,
        status: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })
    if (!existing) return fail("Hospital not found", 404)
    const existingTranslations = await prisma.hospitalTranslation.findMany({
      where: { hospitalId: id },
      select: {
        locale: true,
        name: true,
        location: true,
        heroJson: true,
        aboutJson: true,
        galleryJson: true,
        departmentsJson: true,
        doctorsJson: true,
        accreditationJson: true,
        technologyJson: true,
        visitProcessJson: true,
        reviewsJson: true,
        locationJson: true,
        packagesJson: true,
        faqJson: true,
        ctaJson: true,
        similarJson: true,
      },
    })
    const snapshot = buildHospitalImageSnapshot(
      existing as unknown as Record<string, unknown>,
      existingTranslations as unknown as Array<Record<string, unknown>>
    )

    await prisma.hospital.delete({ where: { id } })
    await prisma.hospitalTranslation.deleteMany({ where: { hospitalId: id } })
    if (snapshot.ids.size > 0) {
      await Promise.allSettled([...snapshot.ids].map((imgId) => deleteImage(imgId)))
    }
    for (const folder of snapshot.folders) {
      await purgePrefixExcept(folder, [])
      await deletePrefixIfEmpty(folder)
    }
    return NextResponse.json({ success: true as const })
  } catch (err) {
    console.error("[hospitals] DELETE error:", err)
    return NextResponse.json({ success: false as const, error: "Failed to delete hospital" }, { status: 500 })
  }
}
