import { listMediaKeysUnderPrefix } from "@/lib/r2-storage"
import { toDoctorFolderSegment } from "@/lib/media-manager/paths"
import type { DoctorMediaSection } from "@/lib/media-manager/types"

export interface DoctorMediaListItem {
  mediaKey: string
  section: DoctorMediaSection | "unknown"
  fileName: string
}

function sectionFromMediaKey(mediaKey: string, doctorSegment: string): DoctorMediaSection | "unknown" {
  const prefix = `doctors/${doctorSegment}/`
  if (!mediaKey.startsWith(prefix)) return "unknown"
  const rest = mediaKey.slice(prefix.length)
  const section = rest.split("/")[0]
  if (
    section === "doctor-photo" ||
    section === "before-after" ||
    section === "gallery" ||
    section === "certificates"
  ) {
    return section
  }
  return "unknown"
}

function fileNameFromMediaKey(mediaKey: string): string {
  const lastSlash = mediaKey.lastIndexOf("/")
  return lastSlash >= 0 ? mediaKey.slice(lastSlash + 1) : mediaKey
}

/** List all media keys for a doctor under `doctors/{doctorName}/`. */
export async function getMediaListByDoctor(doctorName: string): Promise<DoctorMediaListItem[]> {
  const segment = toDoctorFolderSegment(doctorName)
  const prefix = `doctors/${segment}/`
  const keys = await listMediaKeysUnderPrefix(prefix)
  return keys.map((mediaKey) => ({
    mediaKey,
    section: sectionFromMediaKey(mediaKey, segment),
    fileName: fileNameFromMediaKey(mediaKey),
  }))
}
