import axios from 'axios';
import { getErrorMessage, isAuthError, handleError } from './errorHandler';

const api = axios.create({
  baseURL: '/api',
  headers: {
    'Content-Type': 'application/json'
  },
  timeout: 30000 // 30 second timeout
});

// Request interceptor to add auth token
api.interceptors.request.use(
  (config) => {
    const authStorage = localStorage.getItem('auth-storage');
    if (authStorage) {
      try {
        const { state } = JSON.parse(authStorage);
        if (state?.token) {
          config.headers.Authorization = `Bearer ${state.token}`;
        }
      } catch (error) {
        // Silently handle JSON parse errors - don't expose to user
        if (process.env.NODE_ENV !== 'production') {
          console.warn('Failed to parse auth token from storage');
        }
      }
    }
    return config;
  },
  (error) => {
    // Log error in development only
    handleError(error, 'API Request');
    return Promise.reject(error);
  }
);

// Response interceptor to handle errors securely
api.interceptors.response.use(
  (response) => response,
  (error) => {
    // Handle authentication errors
    if (isAuthError(error)) {
      // Clear auth and redirect to login
      localStorage.removeItem('auth-storage');
      
      // Only redirect if not already on login page
      if (window.location.pathname !== '/login') {
        window.location.href = '/login';
      }
    }
    
    // Log error (sanitized in production)
    handleError(error, 'API Response');
    
    return Promise.reject(error);
  }
);

// Utility function to proxy external logo URLs
export const getProxiedLogoUrl = (logoUrl) => {
  if (!logoUrl) return logoUrl;
  
  // Check if it's an external URL (starts with http:// or https://)
  if (logoUrl.startsWith('http://') || logoUrl.startsWith('https://')) {
    // Proxy external URLs through our backend to handle CORS
    return `/api/logo-proxy?url=${encodeURIComponent(logoUrl)}`;
  }
  
  // Return local URLs as-is
  return logoUrl;
};

export default api;
