import axios from "axios";

export const API_BASE_URL = import.meta.env.VITE_API_URL ?? "/api";

export const tokenStorage = {
  get: () => sessionStorage.getItem("accessToken"),
  set: (token) => {
    if (token) sessionStorage.setItem("accessToken", token);
  },
  clear: () => sessionStorage.removeItem("accessToken"),
};

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 12_000,
  headers: { Accept: "application/json" },
});

api.interceptors.request.use((config) => {
  const token = tokenStorage.get();
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      tokenStorage.clear();
      window.dispatchEvent(new CustomEvent("auth:unauthorized"));
    }

    return Promise.reject({
      status: error.response?.status ?? 0,
      message: error.response?.data?.error?.message ?? error.response?.data?.message ?? "Не удалось выполнить запрос",
      fieldErrors: error.response?.data?.error?.errors ?? error.response?.data?.errors ?? error.response?.data?.fieldErrors,
    });
  },
);

export function unwrap(response) {
  return response.data?.data ?? response.data;
}

export { api };
