import i18n from '@/config/i18n';
import { ACCESS_TOKEN_KEY } from '@/providers/AuthProvider';
import axios from 'axios';

const apiClient = axios.create({
  // Define the base URL for all API requests
  baseURL: import.meta.env.VITE_API_URL,

  // Set a timeout for requests (e.g., 10 seconds)
  timeout: 30000,

  // Set default headers
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json',
  },
});

// --- Request Interceptor ---
// This runs BEFORE each request is sent
apiClient.interceptors.request.use(
  (config) => {
    const token = sessionStorage.getItem(ACCESS_TOKEN_KEY);
    if (token) {
      // Add the authorization token to the headers
      config.headers.Authorization = `Bearer ${token}`;
    }

    const currentLang = i18n.language;
    if (currentLang) {
      // If language is 'fa', send 'fa-IR', otherwise send the language code as is
      config.headers['Accept-Language'] =
        currentLang === 'fa' ? 'fa-IR' : 'en-US';
    }

    return config;
  },
  (error) => {
    // Handle request errors
    return Promise.reject(error);
  },
);

// --- Response Interceptor ---
// This runs AFTER a response is received
// TODO: set global post api logic
// apiClient.interceptors.response.use(
//   (response) => {
//     // Any status code within the 2xx range will trigger this function
//     return response;
//   },
//   (error) => {
//     // Handle common errors globally
//     if (error.response?.status === 401) {
//       // e.g., redirect to login page if unauthorized
//       console.error("Unauthorized! Redirecting to login...");
//       // window.location.href = '/login';
//     }
//     return Promise.reject(error);
//   }
// );

export default apiClient;
