import { displayFileName } from "@/lib/drive/display-file-name"

/** Next "Type sans titre" / "Type sans titre N" label for a folder listing. */
export function nextUntitledName(
  siblingNames: string[],
  typeLabel: string,
  ext = ""
): string {
  const base = `${typeLabel} sans titre`
  const normalized = siblingNames.map((n) => displayFileName(n))
  const hasExact = (candidate: string) =>
    normalized.some((n) => n === candidate || n === candidate + ext)

  if (!hasExact(base)) {
    return ext ? `${base}${ext}` : base
  }

  let n = 2
  while (hasExact(`${base} ${n}`)) {
    n += 1
  }
  return ext ? `${base} ${n}${ext}` : `${base} ${n}`
}

export function resolveRenameName(file: { name: string; type: string }, input: string): string {
  const trimmed = input.trim()
  if (!trimmed) {
    throw new Error("Nom vide")
  }
  const safe = trimmed.replace(/\//g, "")
  if (file.type === "directory") {
    return safe
  }
  const rawName = displayFileName(file.name)
  const dot = rawName.lastIndexOf(".")
  const ext = dot > 0 ? rawName.slice(dot) : ""
  if (ext && !safe.endsWith(ext)) {
    return safe + ext
  }
  return safe
}
