import { create } from 'apisauce';

const API_BASE_URL = (import.meta as any).env?.VITE_API_URL || '/api';

const client = create({
    baseURL: API_BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
    timeout: 30000,
});

// Interceptor for Auth Token
client.addRequestTransform((request) => {
    const token = localStorage.getItem('token');
    if (token && request.headers) {
        request.headers.Authorization = `Bearer ${token}`;
    }
});

// Response transform for global error handling
client.addResponseTransform((response) => {
    if (!response.ok) {
        if (response.status === 401) {
            const token = localStorage.getItem('token');
            console.error('Unauthorized access - potential token expiration. Token exists in localStorage:', !!token);
            console.error('Full 401 Response Details:', {
                url: response.config?.url,
                method: response.config?.method,
                data: response.data
            });
            // Dispatch global event for App to handle logout
            window.dispatchEvent(new Event('auth:logout'));
        }
    }
});

export default client;
