import axios from 'axios';

const API_URL = process.env.REACT_APP_BACKEND_URL;
const BASENAME = process.env.REACT_APP_BASENAME || '';

export const api = axios.create({
  baseURL: `${API_URL}/api`,
  timeout: 30000, // 30 second timeout for all requests
});

// Request interceptor - add auth token
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('[API] Request error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor - handle errors and retries
api.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    const config = error.config;

    // Handle 401 Unauthorized - session expired
    if (error.response && error.response.status === 401) {
      // Don't redirect if it's a login request or auth check
      const isAuthRequest = config?.url?.includes('/auth/login') ||
                           config?.url?.includes('/auth/me') ||
                           config?.url?.includes('/auth/permissions');

      if (!isAuthRequest) {
        console.warn('[API] Session expired - redirecting to login');

        // Clear auth state
        localStorage.removeItem('token');

        // Dispatch custom event for components to react
        window.dispatchEvent(new CustomEvent('auth:session-expired'));

        // Redirect to login with session expired message
        // Use replace to prevent back button issues
        // Include BASENAME to support subpath deployments
        const currentPath = window.location.pathname;
        const loginPath = `${BASENAME}/login?session=expired`;
        if (!currentPath.includes('/login')) {
          window.location.replace(loginPath);
        }
      }

      return Promise.reject(error);
    }

    // Don't retry if we've already retried or if it's a client error (4xx)
    if (!config || config.__isRetry || (error.response && error.response.status < 500)) {
      console.error('[API] Request failed:', {
        url: config?.url,
        method: config?.method,
        status: error.response?.status,
        message: error.message,
        data: error.response?.data
      });
      return Promise.reject(error);
    }

    // Mark as retry to prevent infinite loops
    config.__isRetry = true;

    // Retry after 1 second for server errors or network issues
    console.warn('[API] Retrying request after 1s:', {
      url: config.url,
      method: config.method,
      error: error.message
    });

    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(api.request(config));
      }, 1000);
    });
  }
);

export default api;
