import axios from 'axios';

const api = axios.create({
    baseURL: process.env.NEXT_PUBLIC_API_URL || '',
    validateStatus: (status) => status >= 200 && status < 300,
    withCredentials: true,
});

// Response interceptor for error handling
api.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response && error.response.status === 401) {
            const url: string = error.config?.url || '';
            const isAuthCheck =
                url.includes('/auth/login') ||
                url.includes('/auth/me') ||
                url.includes('/auth/mfa/');         // mfa verify + forced-setup
            const path = typeof window !== 'undefined' ? window.location.pathname : '';
            const onAuthPage = path === '/login' || path.startsWith('/mfa-setup');
            if (!isAuthCheck && !onAuthPage && typeof window !== 'undefined') {
                window.location.href = '/login';
            }
        }
        return Promise.reject(error);
    }
);

export default api;
