import { createApiClient } from "hse-auth";

function clearContentType(headers) {
  if (!headers) return;
  if (typeof headers.delete === "function") {
    headers.delete("Content-Type");
    headers.delete("content-type");
    return;
  }
  delete headers["Content-Type"];
  delete headers["content-type"];
}

const api = createApiClient({
  baseURL: import.meta.env.VITE_API_BASE_URL || "/api/ptw",
});

api.interceptors.request.use((config) => {
  const isFormData =
    typeof FormData !== "undefined" && config.data instanceof FormData;

  if (isFormData) {
    clearContentType(config.headers);
  } else if (
    config.data != null &&
    typeof config.data === "object" &&
    !(config.data instanceof URLSearchParams) &&
    !(config.data instanceof ArrayBuffer)
  ) {
    config.headers["Content-Type"] = "application/json";
  }

  return config;
});

export {
  getStoredAuth,
  setStoredAuth,
  clearStoredAuth as logout,
  AUTH_STORAGE_KEY,
} from "hse-auth";

export function fileUrl(path) {
  const base = (import.meta.env.VITE_API_BASE_URL || "/api/ptw").replace(
    /\/$/,
    ""
  );
  const clean = path.startsWith("/") ? path : `/${path}`;
  return `${base}${clean}`;
}

export default api;
