import { extname } from "node:path";

/** Multer file shape we rely on (subset of Express.Multer.File). */
export interface UploadedFileLike {
  buffer: Buffer;
  originalname?: string;
  mimetype?: string;
  size?: number;
}

const MIME_EXT: Record<string, string> = {
  "application/pdf": ".pdf",
  "image/jpeg": ".jpg",
  "image/png": ".png",
  "image/gif": ".gif",
  "image/tiff": ".tif",
  "image/bmp": ".bmp",
};

/** File extension for a stored blob, from the original name, else the mimetype. */
export function extForUpload(file: UploadedFileLike): string {
  const fromName = file.originalname ? extname(file.originalname).toLowerCase() : "";
  if (fromName) return fromName;
  return (file.mimetype && MIME_EXT[file.mimetype]) || "";
}

/** Download filename for a stored document, from its key + document type. */
export function downloadName(storageKey: string, documentType: string): string {
  const ext = extname(storageKey) || "";
  const base = documentType.replace(/[^\w.-]+/g, "_") || "document";
  return base.toLowerCase().endsWith(ext.toLowerCase()) ? base : `${base}${ext}`;
}
