/**
 * This bootstrap file sets up our JavaScript dependencies and configuration
 */

import axios from 'axios';

// Set axios defaults
window.axios = axios;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;

// API base URL - change this to your actual API endpoint in production
window.axios.defaults.baseURL = process.env.MIX_API_URL || '/api';

// Add a request interceptor to include the CSRF token
axios.interceptors.request.use(
  config => {
    // Get the CSRF token from the meta tag if it exists
    const token = document.head.querySelector('meta[name="csrf-token"]');
    
    if (token) {
      config.headers['X-CSRF-TOKEN'] = token.content;
    }
    
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Add a response interceptor to handle common errors
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    // Handle 401 Unauthorized errors (redirect to login)
    if (error.response && error.response.status === 401) {
      window.location.href = '/login';
    }
    
    // Handle 419 CSRF token mismatch errors (reload the page)
    if (error.response && error.response.status === 419) {
      window.location.reload();
    }
    
    return Promise.reject(error);
  }
);

// Log environment
console.log(`Running in ${process.env.NODE_ENV || 'development'} mode`); 