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

/** Dossier par défaut lors de l’export mail → Drive. */
export const MAIL_DRIVE_DEFAULT_FOLDER = "/"

export function normalizeMailDriveFolder(folderPath: string): string {
  const trimmed = folderPath.trim() || MAIL_DRIVE_DEFAULT_FOLDER
  const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`
  const cleaned = withSlash.replace(/\/+/g, "/")
  if (cleaned === "" || cleaned === "//") return MAIL_DRIVE_DEFAULT_FOLDER
  return cleaned.replace(/\/$/, "") || MAIL_DRIVE_DEFAULT_FOLDER
}

export function mailDriveFolderPathLabel(folderPath: string): string {
  const folder = normalizeMailDriveFolder(folderPath)
  if (folder === "/") return "Mon Drive"
  return folder
    .slice(1)
    .split("/")
    .map((segment) => displayFileName(segment))
    .join(" / ")
}

/** Dossier parent affiché (chemin fichier complet). */
export function mailDriveFolderLabel(filePath: string): string {
  const normalized = filePath.replace(/\/+/g, "/")
  const idx = normalized.lastIndexOf("/")
  if (idx <= 0) return "Mon Drive"
  return mailDriveFolderPathLabel(normalized.slice(0, idx))
}

export function mailDriveFolderHref(folderPath: string): string {
  const segments = normalizeMailDriveFolder(folderPath)
    .replace(/^\//, "")
    .split("/")
    .filter(Boolean)
  if (segments.length === 0) return "/drive"
  return `/drive/folders/${segments.map((s) => encodeURIComponent(s)).join("/")}`
}

export function mailDriveParentFolder(filePath: string): string {
  const normalized = filePath.replace(/\/+/g, "/")
  const idx = normalized.lastIndexOf("/")
  if (idx <= 0) return MAIL_DRIVE_DEFAULT_FOLDER
  return normalized.slice(0, idx)
}

export function mailDriveSaveSuccessMessage(folderPath: string): string {
  const label = mailDriveFolderPathLabel(folderPath)
  if (label === "Mon Drive") {
    return "Pièce jointe enregistrée à la racine de Mon Drive"
  }
  return `Pièce jointe enregistrée dans ${label}`
}

export function mailDriveSaveErrorMessage(err: unknown): string {
  if (err instanceof ApiRequestError) {
    if (err.code === "drive.quota_exceeded" || err.status === 507) {
      return "Espace de stockage Drive insuffisant"
    }
    if (err.code === "drive_unavailable") {
      return "UltiDrive est indisponible"
    }
  }
  return "Impossible d'enregistrer dans UltiDrive"
}

export function mailDriveFileHref(filePath: string): string {
  const normalized = filePath.replace(/\/+/g, "/")
  const idx = normalized.lastIndexOf("/")
  if (idx <= 0) return "/drive"
  return mailDriveFolderHref(normalized.slice(0, idx))
}
