import axios from 'axios';
import { API_URL } from './Constant';

const URL_API = `${API_URL}/api`

const axiosInstance = axios.create({
  baseURL: URL_API,
});

axiosInstance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

const refreshAccessToken = async () => {
  try {
    const response = await axios.post(`${URL_API}/refreshToken`, {}, { withCredentials: true });
    const token = response.data.payload.TOKEN;

    localStorage.setItem('token', token); 
    console.log('token refreshed');
    return token;
  } catch (error) {
    console.error('Failed to refresh token', error);
    localStorage.removeItem('token'); 
    window.location.href = '/login';
    throw error;
  }
};

axiosInstance.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;
    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;  
      try {
        const newAccessToken = await refreshAccessToken(); 
        originalRequest.headers.Authorization = newAccessToken;
        return axiosInstance(originalRequest);
      } catch (err) {
        window.location.href = '/login';
        return Promise.reject(err);
      }
    }else if (error.response.status === undefined) {
      window.location.href = '/login';
    }

    return Promise.reject(error);
  }
);

export default axiosInstance;
