import axios from 'axios';

const API_URL = process.env.REACT_APP_API_URL || '/api';

// Create axios instance
// Auth läuft über ein httpOnly-Cookie (vom Server gesetzt) — kein Token in JS-lesbarem Storage,
// damit ein XSS-Treffer das Session-Token nicht einfach auslesen kann.
const api = axios.create({
    baseURL: API_URL,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json',
    },
});

// Response interceptor to handle errors globally
api.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        if (error.response) {
            // Handle 401 Unauthorized - token expired or invalid
            if (error.response.status === 401) {
                localStorage.removeItem('user');
                window.location.href = '/login';
            }

            // Return the error response for handling in components
            return Promise.reject(error.response.data);
        } else if (error.request) {
            // Network error
            return Promise.reject({
                status: 'error',
                message: 'Network error. Please check your connection.',
            });
        } else {
            // Re-throw original error
            return Promise.reject(error);
        }
    }
);

export default api;
