import axios from 'axios';

// Create axios instance
const apiClient = axios.create({
    baseURL: '/api',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
});

// Request interceptor
apiClient.interceptors.request.use(
    (config) => {
        // Add CSRF token if available
        const token = document.querySelector('meta[name="csrf-token"]')?.content;
        if (token) {
            config.headers['X-CSRF-TOKEN'] = token;
        }

        // Add auth token if user is logged in
        // You can get this from Laravel's session or localStorage
        const authToken = localStorage.getItem('auth_token');
        if (authToken) {
            config.headers['Authorization'] = `Bearer ${authToken}`;
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// Response interceptor
apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
        // Handle common errors
        if (error.response?.status === 401) {
            // Handle unauthorized
            console.error('Unauthorized');
        } else if (error.response?.status === 422) {
            // Handle validation errors
            console.error('Validation errors:', error.response.data.errors);
        }

        return Promise.reject(error);
    }
);

export function createApiClient() {
    return apiClient;
}

export default apiClient;

