import { formatDate, type DateLanguage } from "@/lib/date-utils";

const API_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1";

export function toBackendUrl(path?: string | null) {
  if (!path) {
    return undefined;
  }

  if (path.startsWith("http")) {
    return path;
  }

  const backendBase = API_URL.replace(/\/api(?:\/v\d+)?\/?$/, "");
  return `${backendBase}${path.startsWith("/") ? path : `/${path}`}`;
}

export function formatIssueDate(
  value?: string | Date | null,
  language: DateLanguage = "en",
) {
  const formattedDate = formatDate(value, language);

  return formattedDate === "-" ? null : formattedDate;
}

export function getAttachmentName(path?: string | null) {
  if (!path) {
    return "Issue attachment";
  }

  const cleanPath = path.split("?")[0] ?? path;
  const fileName = cleanPath.split("/").filter(Boolean).pop();

  if (!fileName) {
    return "Issue attachment";
  }

  try {
    return decodeURIComponent(fileName);
  } catch {
    return fileName;
  }
}
