import axios, { AxiosError } from 'axios';
import type { InternalAxiosRequestConfig } from 'axios';
import { ENV } from '../config/env';
import { message } from 'antd';

const jwtAxios = axios.create({
  baseURL: "/api",
  timeout: 60000,
  headers: { 'Content-Type': 'application/json' },
});

jwtAxios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const token = localStorage.getItem(ENV.ACCESS_TOKEN_STORAGE_KEY);
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => Promise.reject(error)
);

// jwtAxios.interceptors.response.use(
//   (response) => response,
//   (error: AxiosError) => {
//     if (error.response?.status === 401) {
//       setAuthToken(null);
//       if (window.location.pathname !== '/login') {
//         message.error('Session expired. Please log in again.');
//         window.location.href = '/login';
//       }
//     } else if (error.response?.status === 403) {
//       if (window.location.pathname !== '/error/403') {
//         message.error('Access denied.');
//         window.location.href = '/error/403';
//       }
//     }
//     return Promise.reject(error);
//   }
// );

jwtAxios.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    const status = error.response?.status;

    if (status === 401) {
      setAuthToken(null);

      if (window.location.pathname !== "/login") {
        message.error("Session expired. Please log in again.");
        window.location.href = "/login";
      }
    } else if (status === 403) {
      message.error("You do not have permission to perform this action.");

      // Only redirect if you specifically want a global 403 page
      if (window.location.pathname !== "/error/403") {
        window.location.href = "/error/403";
      }
    }

    return Promise.reject(error);
  }
);

export const setAuthToken = (token: string | null) => {
  if (token) {
    jwtAxios.defaults.headers.common.Authorization = `Bearer ${token}`;
    localStorage.setItem(ENV.ACCESS_TOKEN_STORAGE_KEY, token);
  } else {
    delete jwtAxios.defaults.headers.common.Authorization;
    localStorage.removeItem(ENV.ACCESS_TOKEN_STORAGE_KEY);
    localStorage.removeItem(ENV.USER_STORAGE_KEY);
  }
};

export default jwtAxios;