import axios from 'axios';

const axiosServices = axios.create({
  baseURL: process.env.REACT_APP_URL || 'http://localhost:3010/',
  withCredentials: true, // Allow cookies to be sent with requests
  headers: {
    'Content-Type': 'application/json'
  }
});

// ==============================|| AXIOS - INTERCEPTOR ||============================== //

axiosServices.interceptors.response.use(
  (response) => response,
  (error) => {
    // Log error for debugging
    console.error('API Error:', error.response?.status, error.message);

    // Redirect to login on 401 (Unauthorized)
    if (error.response?.status === 401 && !window.location.href.includes('/login')) {
      localStorage.removeItem('user');
      window.location = '/login';
    }

    // Return error details
    return Promise.reject((error.response && error.response.data) || { message: error.message });
  }
);

export default axiosServices;
