import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

interface ApiConfig {
    baseURL?: string;
    timeout?: number;
    headers?: Record<string, string>;
}

// Clean base URL once at top-level
const rawBaseUrl = import.meta.env.VITE_API_BASE_URL || '';
const cleanedBaseUrl = rawBaseUrl.replace(/\/$/, '');

const DEFAULT_CONFIG: ApiConfig = {
    baseURL: cleanedBaseUrl,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json',
    },
};

export const api = async <T = any>(
    method: 'get' | 'post' | 'put' | 'delete' | 'patch',
    url: string,
    data?: any,
    params?: any,
    responseType: 'json' | 'blob' | 'text' = 'json',
    timeout?: number,
    useAuth: boolean = true
): Promise<AxiosResponse<T>> => {
    const config: AxiosRequestConfig = {
        ...DEFAULT_CONFIG,
        method,
        url,
        data,
        params,
        responseType,
        timeout: timeout || DEFAULT_CONFIG.timeout,
    };

    if (useAuth) {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers = {
                ...config.headers,
                Authorization: `Bearer ${token}`,
            };
        }
    }

    try {
        return await axios(config);
    } catch (error) {
        if (axios.isAxiosError(error)) {
            if (error.response?.status === 401) {
                localStorage.removeItem('token');
                window.location.href = '/login';
            }
        }
        throw error;
    }
};
