import axios from 'axios';

/**
 * Axios instance with error handling interceptors
 * Handles HTTP status codes and redirects to appropriate error pages
 */

// Create axios instance
const apiClient = axios.create({
  baseURL: window._env_?.API_URL || '',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // For session cookies
});

/**
 * Response interceptor for error handling
 */
apiClient.interceptors.response.use(
  (response) => {
    // Pass through successful responses
    return response;
  },
  (error) => {
    if (error.response) {
      const { status } = error.response;

      // Handle specific HTTP status codes
      switch (status) {
        case 403:
          // Forbidden - redirect to 403 page
          window.location.href = '/error/403';
          break;

        case 500:
          // Internal Server Error - redirect to 500 page
          window.location.href = '/error/500';
          break;

        case 502:
          // Bad Gateway - redirect to 502 page
          window.location.href = '/error/502';
          break;

        case 503:
          // Service Unavailable - redirect to 503 page
          window.location.href = '/error/503';
          break;

        default:
          // For other errors, just reject the promise
          break;
      }
    }

    // Always reject the promise so calling code can handle it
    return Promise.reject(error);
  }
);

export default apiClient;
