// src/shared/utils/get-final-allowed-file-types.ts
const extensionToMimeTypes: Record<string, string[]> = {
  png: ["image/png"],
  jpg: ["image/jpeg"],
  jpeg: ["image/jpeg"],
  gif: ["image/gif"],
  pdf: ["application/pdf"],
  dwg: ["application/acad", "application/x-autocad", "application/x-dwg", "image/vnd.dwg"],
  dxf: ["application/dxf", "application/x-dxf", "image/vnd.dxf"],
  dwt: ["application/x-autocad-dwt", "application/x-autocad"],
  bak: ["application/octet-stream"],
  "sv$": ["application/octet-stream"],
  dws: ["application/x-autocad-dws", "application/x-autocad"],
  mxd: ["application/x-esri-map", "application/octet-stream"],
  aprx: ["application/x-esri-arcgis-pro-project", "application/octet-stream"],
  rar: ["application/x-rar-compressed", "application/vnd.rar"],
  zip: ["application/zip"],
};

const mimeToExtensions: Record<string, string[]> = Object.entries(
  extensionToMimeTypes
).reduce((acc, [ext, mimes]) => {
  for (const mime of mimes) {
    if (!acc[mime]) acc[mime] = [];
    acc[mime].push(`.${ext}`);
  }
  return acc;
}, {} as Record<string, string[]>);

const normalizeToken = (token: string) => token.trim().toLowerCase();

export const getAllowedMimeTypesFromAccept = (
  accept: string[] | null | undefined
): string[] => {
  if (!accept || accept.length === 0) return [];

  const mimeSet = new Set<string>();

  for (const rawToken of accept) {
    const token = normalizeToken(rawToken);
    if (!token) continue;

    if (token.includes("/")) {
      mimeSet.add(token);
      continue;
    }

    const extension = token.startsWith(".") ? token.slice(1) : token;
    (extensionToMimeTypes[extension] || []).forEach((mime) => mimeSet.add(mime));
  }

  return Array.from(mimeSet);
};

export const getAllowedExtensionsFromAccept = (
  accept: string[] | null | undefined
): string[] => {
  if (!accept || accept.length === 0) return [];

  const extensionSet = new Set<string>();

  for (const rawToken of accept) {
    const token = normalizeToken(rawToken);
    if (!token) continue;

    if (token.includes("/")) {
      (mimeToExtensions[token] || []).forEach((ext) => extensionSet.add(ext));
      continue;
    }

    const normalizedExtension = token.startsWith(".") ? token : `.${token}`;
    extensionSet.add(normalizedExtension);
  }

  return Array.from(extensionSet);
};

export const getFinalAllowedFileTypes = (
  accept: string[] | null | undefined
): string => {
  if (!accept || accept.length === 0) return "";

  const result = accept.map((token) => normalizeToken(token)).join(",");

  return result;
};
