import axios from "axios";
import { API_BASE_URL } from "../config";

const api = axios.create({
  baseURL: API_BASE_URL,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
  },
});

api.interceptors.request.use((config => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["Authorization"] = `Bearer ${token}`;
  }
  return config;
}));

api.interceptors.response.use(
  response => {
    const payload = response.data;
    if (
      payload &&
      typeof payload === "object" &&
      !Array.isArray(payload) &&
      Object.keys(payload).length === 2 &&
      Object.prototype.hasOwnProperty.call(payload, "data") &&
      Object.prototype.hasOwnProperty.call(payload, "request_id")
    ) {
      response.request_id = payload.request_id;
      response.data = payload.data;
    }
    return response;
  },
  error => {
    const payload = error.response?.data;
    const normalizedMessage = payload?.error?.message || payload?.message;

    if (payload?.error?.message && payload.message === undefined) {
      payload.message = payload.error.message;
    }

    if (
      error.response?.status === 401 &&
      window.location.pathname !== "/login" &&
      window.location.pathname !== "/register" &&
      [
        "Invalid or expired token",
        "Invalid or expired session",
        "Missing authentication",
      ].includes(normalizedMessage)
    ) {
      localStorage.removeItem("token");
      window.location.href = "/login";
      alert("Your session has expired. Please log in again.");
    }
    return Promise.reject(error);
  }
);

export default api;
