const MIME_EXTENSION: Record<string, string> = {
  "application/pdf": ".pdf",
  "application/postscript": ".ai",
  "application/illustrator": ".ai",
  "application/zip": ".zip",
  "application/x-zip-compressed": ".zip",
  "application/vnd.ms-powerpoint": ".ppt",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation":
    ".pptx",
  "application/msword": ".doc",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
    ".docx",
  "audio/mpeg": ".mp3",
  "audio/mp3": ".mp3",
  "video/mp4": ".mp4",
  "image/jpeg": ".jpg",
  "image/png": ".png",
  "image/gif": ".gif",
  "image/webp": ".webp",
};

export function filenameWithExtension(filename: string, mime = ""): string {
  if (hasFileExtension(filename)) return filename;

  const ext = extensionFromMime(mime);
  return ext ? `${filename}${ext}` : filename;
}

export function middleEllipsisFilename(
  filename: string,
  maxLength = 24,
): string {
  if (filename.length <= maxLength) return filename;

  const { base, ext } = splitFilename(filename);
  const ellipsis = "…";
  const availableBaseLength = maxLength - ext.length - ellipsis.length;

  if (availableBaseLength < 3) {
    return `${filename.slice(0, Math.max(1, maxLength - 1))}${ellipsis}`;
  }

  const tailLength = Math.min(
    4,
    Math.floor(availableBaseLength / 2),
    base.length,
  );
  const headLength = availableBaseLength - tailLength;

  if (headLength + tailLength >= base.length) return filename;
  return `${base.slice(0, headLength)}${ellipsis}${base.slice(-tailLength)}${ext}`;
}

export function splitFilename(filename: string): { base: string; ext: string } {
  const dotIndex = filename.lastIndexOf(".");
  if (!hasFileExtension(filename)) return { base: filename, ext: "" };
  return {
    base: filename.slice(0, dotIndex),
    ext: filename.slice(dotIndex),
  };
}

function hasFileExtension(filename: string): boolean {
  const dotIndex = filename.lastIndexOf(".");
  return (
    dotIndex > 0 &&
    dotIndex < filename.length - 1 &&
    filename.length - dotIndex <= 12
  );
}

function extensionFromMime(mime: string): string {
  const cleanMime = mime.toLowerCase().split(";")[0].trim();
  if (!cleanMime) return "";
  if (MIME_EXTENSION[cleanMime]) return MIME_EXTENSION[cleanMime];

  if (cleanMime.startsWith("image/")) return `.${cleanMime.slice(6)}`;
  if (cleanMime.startsWith("video/")) return `.${cleanMime.slice(6)}`;
  if (cleanMime.startsWith("audio/")) return `.${cleanMime.slice(6)}`;

  return "";
}
