import axios from 'axios';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://juryapi.wgi-it.com';

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'Content-Type': 'application/json' },
});

apiClient.interceptors.request.use((config) => {
  if (typeof window === 'undefined') return config;

  const token = window.localStorage.getItem('access');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  return config;
});

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

    if (
      originalRequest?.url?.includes('/api/login/') ||
      originalRequest?.url?.includes('/api/token/refresh/')
    ) {
      return Promise.reject(error);
    }

    if (error.response?.status === 401 && !originalRequest?._retry) {
      originalRequest._retry = true;

      const refresh = typeof window !== 'undefined'
        ? window.localStorage.getItem('refresh')
        : null;

      if (!refresh) return Promise.reject(error);

      try {
        const { data } = await axios.post(`${API_BASE_URL}/api/token/refresh/`, { refresh });

        if (typeof window !== 'undefined') {
          window.localStorage.setItem('access', data.access);
        }

        originalRequest.headers.Authorization = `Bearer ${data.access}`;
        return apiClient(originalRequest);
      } catch (refreshError) {
        if (typeof window !== 'undefined') {
          window.localStorage.clear();
          window.location.assign('/');
        }

        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  },
);

export default apiClient;
