import axios from 'axios';

// Create an Axios instance with base URL and credentials
const api = axios.create({
  baseURL: '/api', // The base URL for your API
  withCredentials: true, // Send cookies with requests
});

// Set up an Axios interceptor to handle token expiration (401 error)
api.interceptors.response.use(
  (response) => response, // If the response is OK, just return it
  async (error) => {
    const originalRequest = error.config;

    if (
      error.response &&
      error.response.status === 401 &&
      !originalRequest._retry
    ) {
      originalRequest._retry = true; // Prevent an infinite retry loop

      // Try refreshing the token
      try {
        await api.post('/auth/refresh-token');
        // Retry the original request with the new token
        return api(originalRequest);
      } catch (refreshError) {
        console.log('originalRequest', originalRequest);
        console.error('Token refresh failed:', refreshError);
        // Handle failed refresh (e.g., redirect to login page)
        window.location.href = '/lobby';
      }
    }

    return Promise.reject(error); // Reject if it's not a 401 or after retry
  }
);

export default api;
