import { router } from '@inertiajs/vue3'
import * as Sentry from "@sentry/vue";
import axios from 'axios'
import i18n from '@/locales/i18n'

// inject the current locale to the inertia request to get the correct 
// error language from the backend
export function setupLocaleInterceptor() {
  router.on('before', (event) => {
    event.detail.visit.headers = {
      ...event.detail.visit.headers,
      'Accept-Language': i18n.global.locale.value,
    }
  })
  router.on('error', (event) => {
    Sentry.captureException(event.detail.errors);
  })
  router.on('exception', (event) => {
    Sentry.captureException(event.detail.exception);
  })

  // Global Axios interceptor to ensure all XHR requests also have the correct locale header
  axios.interceptors.request.use((config) => {
    config.headers['Accept-Language'] = i18n.global.locale.value;
    return config;
  })
}

// Optionally export a configured axios instance directly for reusable requests
export const apiClient = axios;
