import axios from "axios";

export const getToken = () => {
  return localStorage.getItem("token");
};

const Chapar = axios.create({
  baseURL: process.env.NEXT_PUBLIC_API_URL,
  timeout: 100000,
  headers: {
    "Content-type": "application/json",
    "Access-Control-Allow-Origin": "*",
  },
});

// Request interceptor to conditionally add token to headers
Chapar.interceptors.request.use(
  (config) => {
    const token = getToken();
    if (token && !config.isPublic) {
      config.headers.Authorization = "Bearer" + " " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor to handle responses
// Chapar.interceptors.response.use(
//   (response) => {
//     return response.data;
//   },
//   (error) => {
//     const status = error?.response?.status;
//     if (status === 401) {
//       localStorage.removeItem("token");
//       window.location.href = "/login";
//     }
//     return Promise.reject({ error, status });
//   }
// );

export default Chapar;
