import type { ApplicationFile } from "@/data/mockApplications";

export type InferredEvidenceKind = "pdf" | "image" | "docx" | "xlsx" | "link" | "other";

const LINK_RE = /^https?:\/\//i;

/** Guess icon kind from `ApplicationFile.type`, URL, or file name. */
export function inferEvidenceFileKind(
  file: Pick<ApplicationFile, "type" | "url" | "viewUrl"> & { originalName?: string | null },
): InferredEvidenceKind {
  const t = String(file.type || "").toLowerCase();
  const url = String(file.viewUrl || file.url || "");
  if (t === "link" || LINK_RE.test(url)) {
    return "link";
  }
  if (t === "pdf" || t.includes("pdf")) return "pdf";
  if (t === "image" || t === "img" || t.includes("image")) return "image";
  if (t === "docx" || t.includes("word") || t.includes("document")) return "docx";
  if (t === "xlsx" || t.includes("sheet") || t.includes("excel")) return "xlsx";

  const lower = url.toLowerCase();
  const name = (file.originalName || url.split("/").pop() || "").toLowerCase();
  if (LINK_RE.test(url)) return "link";
  if (lower.includes(".pdf") || name.endsWith(".pdf")) return "pdf";
  if (/\.(png|jpe?g|gif|webp|svg)$/i.test(lower) || /\.(png|jpe?g|gif|webp|svg)$/i.test(name)) {
    return "image";
  }
  if (/\.docx?$/i.test(name) || lower.includes(".docx")) return "docx";
  if (/\.xlsx?$/i.test(name) || lower.includes(".xlsx") || name.endsWith(".xls")) return "xlsx";
  if (t) return "other";
  return "other";
}

export function formatEvidenceMimeLabel(mime?: string | null, originalName?: string | null): string {
  if (originalName) return originalName;
  if (!mime) return "Tệp đính kèm";
  const m = mime.toLowerCase();
  if (m.includes("pdf")) return "PDF";
  if (m.startsWith("image/")) return "Hình ảnh";
  if (m.includes("word") || m.includes("document")) return "Word";
  if (m.includes("sheet") || m.includes("excel")) return "Excel";
  return mime;
}
