import axios from 'axios';
import Cookies from 'js-cookie';

const baseURL = import.meta.env.VITE_API_URL;
console.log(baseURL);

export const axiosRealEstateApi = axios.create({
  baseURL: 'https://api.realestateapi.com/v2/',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': import.meta.env.REAL_ESTATE_API_KEY,
    'X-User-Id': 'UniqueUserIdentifier',
  },
});

export const axiosWalkScoreApiInstance = axios.create({
  baseURL: 'https://api.walkscore.com/',
  timeout: 5000,
});

export const axiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    Authorization: 'JWT ' + localStorage.getItem('access_token'),
    'Content-Type': 'application/json',
    Accept: 'application/json',
  },
});

export const cleanAxiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  },
});

export const axiosInstanceCSRF = axios.create({
  baseURL: baseURL,
  timeout: 5000,
  headers: {
    'X-CSRFToken': Cookies.get('csrftoken'), // Include CSRF token in headers
  },
  withCredentials: true,
});

axiosInstance.interceptors.request.use((config) => {
  config.timeout = 100000;
  return config;
});

axiosInstance.interceptors.response.use(
  (response) => response,
  (error) => {
    const originalRequest = error.config;

    // Prevent infinite loop
    if (error.response.status === 401 && originalRequest.url === baseURL + '/token/refresh/') {
      window.location.href = '/authentication/login/';
      //console.log('remove the local storage here')
      return Promise.reject(error);
    }

    if (
      error.response.data.code === 'token_not_valid' &&
      error.response.status == 401 &&
      error.response.statusText == 'Unauthorized'
    ) {
      const refresh_token = localStorage.getItem('refresh_token');

      if (refresh_token) {
        const tokenParts = JSON.parse(atob(refresh_token.split('.')[1]));

        const now = Math.ceil(Date.now() / 1000);
        //console.log(tokenParts.exp)

        if (tokenParts.exp > now) {
          return axiosInstance
            .post('/token/refresh/', { refresh: refresh_token })
            .then((response) => {
              localStorage.setItem('access_token', response.data.access);
              localStorage.setItem('refresh_token', response.data.refresh);

              axiosInstance.defaults.headers['Authorization'] = 'JWT ' + response.data.access;
              originalRequest.headers['Authorization'] = 'JWT ' + response.data.access;

              return axiosInstance(originalRequest);
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log('Refresh token is expired');
          window.location.href = '/authentication/login/';
        }
      } else {
        console.log('Refresh token not available');
        window.location.href = '/authentication/login/';
      }
    }
    return Promise.reject(error);
  },
);
