import { randomBytes } from "crypto"
import type { DoctorMediaSection, HospitalMediaSection } from "@/lib/media-manager/types"
import { DOCTOR_MEDIA_SECTIONS, HOSPITAL_MEDIA_SECTIONS } from "@/lib/media-manager/types"
import { toHospitalFolderSegment } from "@/lib/hospital-db"
import { toProcedureFolderSegment } from "@/lib/procedure-db"
import type { ArticleMediaSection, ProcedureMediaSection } from "@/lib/media-manager/types"
import { ARTICLE_MEDIA_SECTIONS, PROCEDURE_MEDIA_SECTIONS } from "@/lib/media-manager/types"
export function toArticleFolderSegment(value: string): string {
  const normalized = value
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\s-_]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^[-_]+|[-_]+$/g, "")
  return normalized || "untitled-article"
}

export function toDoctorFolderSegment(doctorName: string): string {
  const normalized = doctorName
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9\s-_]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^[-_]+|[-_]+$/g, "")
  return normalized || "untitled-doctor"
}

/** Maps legacy UI/API section values to canonical R2 folder segments. */
export function normalizeDoctorSection(section: string): DoctorMediaSection {
  const raw = section.trim().toLowerCase()
  if (raw === "profile" || raw === "doctor-photo" || raw === "doctor_photo") {
    return "doctor-photo"
  }
  if (raw === "before-after" || raw === "before_after") return "before-after"
  if (raw === "gallery") return "gallery"
  if (raw === "certificates" || raw === "certificate") return "certificates"
  if ((DOCTOR_MEDIA_SECTIONS as readonly string[]).includes(raw)) {
    return raw as DoctorMediaSection
  }
  return "doctor-photo"
}

export function sanitizeFileBaseName(name: string): string {
  const base = name.trim().replace(/\.[^.]+$/, "")
  const normalized = base
    .toLowerCase()
    .replace(/[^a-z0-9\s-_]/g, "")
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-")
    .replace(/^[-_]+|[-_]+$/g, "")
  return normalized
}

/** Random hex file name (server). */
export function generateFileName(originalName?: string): string {
  const fromOriginal = originalName ? sanitizeFileBaseName(originalName) : ""
  if (fromOriginal) return fromOriginal
  return randomBytes(8).toString("hex")
}

/** R2 prefix root for doctor media: `doctors/{name-segment}` */
export function doctorMediaBaseForName(name: string): string {
  return `doctors/${toDoctorFolderSegment(name)}`
}

/** R2 prefix: `doctors/{doctorSlug}/{section}` */
export function generateDoctorPrefix(doctorName: string, section: string): string {
  const segment = toDoctorFolderSegment(doctorName)
  const normalizedSection = normalizeDoctorSection(section)
  return `doctors/${segment}/${normalizedSection}`
}

/** Full media key without extension: `doctors/{doctorSlug}/{section}/{fileName}` */
export function generateDoctorPath(doctorName: string, section: string, fileName: string): string {
  const prefix = generateDoctorPrefix(doctorName, section)
  const base = sanitizeFileBaseName(fileName) || generateFileName()
  return `${prefix}/${base}`
}

/** Maps legacy UI/API section values to canonical hospital R2 folder segments. */
export function normalizeHospitalSection(section: string): HospitalMediaSection {
  const raw = section.trim().toLowerCase()
  if (raw === "main" || raw === "main-photo" || raw === "main_photo" || raw === "profile") {
    return "main-photo"
  }
  if (raw === "before-after" || raw === "before_after") return "before-after"
  if (raw === "gallery") return "gallery"
  if (
    raw === "certificates" ||
    raw === "certificate" ||
    raw === "accreditation-logo" ||
    raw === "accreditation_logo" ||
    raw === "accreditation-certificate" ||
    raw === "accreditation_certificate"
  ) {
    return "certificates"
  }
  if ((HOSPITAL_MEDIA_SECTIONS as readonly string[]).includes(raw)) {
    return raw as HospitalMediaSection
  }
  return "gallery"
}

/** R2 prefix: `hospitals/{hospitalSlug}/{section}` */
export function generateHospitalPrefix(hospitalSlug: string, section: string): string {
  const segment = toHospitalFolderSegment(hospitalSlug)
  const normalizedSection = normalizeHospitalSection(section)
  return `hospitals/${segment}/${normalizedSection}`
}

/** Full media key without extension: `hospitals/{hospitalSlug}/{section}/{fileName}` */
export function generateHospitalPath(hospitalSlug: string, section: string, fileName: string): string {
  const prefix = generateHospitalPrefix(hospitalSlug, section)
  const base = sanitizeFileBaseName(fileName) || generateFileName()
  return `${prefix}/${base}`
}

/** Maps legacy UI/API section values to canonical procedure R2 folder segments. */
export function normalizeProcedureSection(section: string): ProcedureMediaSection {
  const raw = section.trim().toLowerCase()
  if (
    raw === "before-after-hero" ||
    raw === "before_after_hero" ||
    raw === "procedure-hero" ||
    raw === "procedure-basic-before-after"
  ) {
    return "before-after-hero"
  }
  if (raw === "procedure-result" || raw === "before-after-gallery" || raw === "before_after_gallery" || raw === "procedure-gallery-before-after") {
    return "before-after-gallery"
  }
  if (
    raw === "before-after" ||
    raw === "before_after" ||
    raw === "procedure-before" ||
    raw === "procedure-after"
  ) {
    return "before-after-hero"
  }
  if (raw === "overview" || raw === "procedure-overview" || raw === "procedure-overview-card") {
    return "overview"
  }
  if (raw === "reviews" || raw === "procedure-reviews" || raw === "procedure-avatar") {
    return "reviews"
  }
  if (
    raw === "main" ||
    raw === "main-photo" ||
    raw === "main_photo" ||
    raw === "profile" ||
    raw === "procedure" ||
    raw === "procedure-main"
  ) {
    return "main-photo"
  }
  /** @deprecated overview card lived under `gallery`. */
  if (raw === "gallery") {
    return "overview"
  }
  /** @deprecated review avatars used `certificates` folder. */
  if (raw === "certificates" || raw === "certificate") {
    return "reviews"
  }
  if ((PROCEDURE_MEDIA_SECTIONS as readonly string[]).includes(raw)) {
    return raw as ProcedureMediaSection
  }
  return "overview"
}

/** R2 prefix: `procedures/{procedureSlug}/{section}` */
export function generateProcedurePrefix(procedureSlug: string, section: string): string {
  const segment = toProcedureFolderSegment(procedureSlug)
  const normalizedSection = normalizeProcedureSection(section)
  return `procedures/${segment}/${normalizedSection}`
}

/** Full media key without extension: `procedures/{procedureSlug}/{section}/{fileName}` */
export function generateProcedurePath(procedureSlug: string, section: string, fileName: string): string {
  const prefix = generateProcedurePrefix(procedureSlug, section)
  const base = sanitizeFileBaseName(fileName) || generateFileName()
  return `${prefix}/${base}`
}

/** Maps legacy UI/API section values to canonical article R2 folder segments. */
export function normalizeArticleSection(section: string): ArticleMediaSection {
  const raw = section.trim().toLowerCase()
  if (raw === "cover" || raw === "cover-image" || raw === "cover_image" || raw === "hero" || raw === "main") {
    return "cover-image"
  }
  if (
    raw === "content-images" ||
    raw === "content_images" ||
    raw === "content" ||
    raw === "inline" ||
    raw === "editor"
  ) {
    return "content-images"
  }
  if (raw === "gallery") return "gallery"
  if (raw === "seo-images" || raw === "seo_images" || raw === "seo") return "seo-images"
  if ((ARTICLE_MEDIA_SECTIONS as readonly string[]).includes(raw)) {
    return raw as ArticleMediaSection
  }
  return "content-images"
}

/** R2 prefix: `articles/{articleSlug}/{section}` */
export function generateArticlePrefix(articleSlug: string, section: string): string {
  const segment = toArticleFolderSegment(articleSlug)
  const normalizedSection = normalizeArticleSection(section)
  return `articles/${segment}/${normalizedSection}`
}

/** Full media key without extension: `articles/{articleSlug}/{section}/{fileName}` */
export function generateArticlePath(articleSlug: string, section: string, fileName: string): string {
  const prefix = generateArticlePrefix(articleSlug, section)
  const base = sanitizeFileBaseName(fileName) || generateFileName()
  return `${prefix}/${base}`
}
