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 | null) {
  if (!value) {
    return null;
  }

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) {
    return null;
  }

  return date.toLocaleDateString("en-US", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });
}

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;
  }
}
