import axios from 'axios';
import { store } from '../store';

// Create the base axios instance
const apiClient = axios.create({
  baseURL: import.meta.env.VITE_API_URL || '/api',
  headers: {
    'Content-Type': 'application/json',
  },
});

// Add request interceptor to include API key in headers if available
apiClient.interceptors.request.use(
  (config) => {
    const state = store.getState();
    const apiKey = state.auth.apiKey;
    
    if (apiKey) {
      config.headers['X-API-Key'] = apiKey;
    }
    
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Add response interceptor to handle common errors
apiClient.interceptors.response.use(
  (response) => response,
  (error) => {
    // Handle 401 unauthorized errors
    if (error.response && error.response.status === 401) {
      store.dispatch({ type: 'auth/logout' });
    }
    
    return Promise.reject(error);
  }
);

export default apiClient;