// public/js/apiConfig.js

class ApiConfig {
    constructor() {
        this.baseURL = this.getBaseURL();
        this.timeout = 10000;
        this.retryAttempts = 3;
        this.retryDelay = 1000;
    }

    getBaseURL() {
        const hostname = window?.location.hostname || '';
        const port = window?.location.port || '';

        if (hostname === 'localhost' || hostname === '127.0.0.1') {
            return `http://localhost:${port === '3000' ? '3001' : '3001'}`;
        }

        if (hostname.includes('staging') || hostname.includes('dev')) {
            return 'https://api-staging.yourdomain.com';
        }

        return 'https://api.yourdomain.com';
    }

    createAxiosInstance() {
        const instance = axios.create({
            baseURL: this.baseURL,
            timeout: this.timeout,
            headers: { 'Content-Type': 'application/json' }
        });

        instance.interceptors.request.use(
            (config) => {
                const token = localStorage.getItem('jwtToken') || sessionStorage.getItem('jwtToken');
                if (token) {
                    config.headers.Authorization = `Bearer ${token}`;
                }
                config.metadata = { startTime: new Date() };
                return config;
            },
            (error) => Promise.reject(error)
        );

        instance.interceptors.response.use(
            (response) => {
                if (this.isDevelopment()) {
                    const end = new Date();
                    const duration = end - (response.config.metadata?.startTime || end);
                    console.log(`✅ ${response.config.url} (${duration}ms)`);
                }
                return response;
            },
            async (error) => {
                const originalRequest = error.config;

                if (error.response?.status === 401 && !originalRequest._retry) {
                    originalRequest._retry = true;
                    this.handleUnauthorized();
                    return Promise.reject(error);
                }

                if (this.shouldRetry(error)) {
                    originalRequest._retryCount = (originalRequest._retryCount || 0) + 1;

                    if (originalRequest._retryCount <= this.retryAttempts) {
                        const delay = this.retryDelay * Math.pow(2, originalRequest._retryCount - 1);
                        await this.sleep(delay);
                        return instance(originalRequest);
                    }
                }

                return Promise.reject(error);
            }
        );

        return instance;
    }

    shouldRetry(error) {
        return (
            !error.response ||
            error.response.status >= 500 ||
            error.code === 'ECONNABORTED'
        );
    }

    handleUnauthorized() {
        localStorage.removeItem('authToken');
        sessionStorage.removeItem('authToken');

        if (typeof window !== 'undefined' && window.location) {
            console.warn('🔐 Session expired. Redirecting to login.');
            window.location.href = '/auth/login';
        }
    }

    isDevelopment() {
        return window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
    }

    sleep(ms) {
        return new Promise((res) => setTimeout(res, ms));
    }
}

// ✅ Initialize and expose globally
const apiConfig = new ApiConfig();
const api = apiConfig.createAxiosInstance();

window.api = api;
window.apiConfig = apiConfig;

// Optional: Global error handler
window.addEventListener('unhandledrejection', (event) => {
    if (event.reason?.isAxiosError) {
        console.error('❌ Unhandled API Error:', {
            url: event.reason.config?.url,
            method: event.reason.config?.method,
            status: event.reason.response?.status,
            message: event.reason.message
        });
    }
});
