const API_URL = '/api';

export const getAuthToken = () => localStorage.getItem('token');
export const setAuthToken = (token: string) => localStorage.setItem('token', token);
export const removeAuthToken = () => localStorage.removeItem('token');

const headers = () => {
    const token = getAuthToken();
    return {
        'Content-Type': 'application/json',
        ...(token ? { Authorization: `Bearer ${token}` } : {})
    };
};

const handleResponse = async (res: Response) => {
    if (res.status === 401) {
        removeAuthToken();
        if (window.location.pathname !== '/login') {
            window.location.href = '/login';
        }
        throw new Error('Unauthorized');
    }
    if (!res.ok) {
        const text = await res.text();
        try {
            const json = JSON.parse(text);
            throw new Error(json.message || json.error || text);
        } catch {
            throw new Error(text);
        }
    }
    return res.json();
};

export const api = {
    get: async <T = any>(endpoint: string): Promise<T> => {
        const res = await fetch(`${API_URL}${endpoint}`, { headers: headers() });
        return handleResponse(res);
    },
    post: async <T = any>(endpoint: string, data: any): Promise<T> => {
        const res = await fetch(`${API_URL}${endpoint}`, {
            method: 'POST',
            headers: headers(),
            body: JSON.stringify(data)
        });
        return handleResponse(res);
    },
    put: async <T = any>(endpoint: string, data: any): Promise<T> => {
        const res = await fetch(`${API_URL}${endpoint}`, {
            method: 'PUT',
            headers: headers(),
            body: JSON.stringify(data)
        });
        return handleResponse(res);
    },
    delete: async <T = any>(endpoint: string): Promise<T> => {
        const res = await fetch(`${API_URL}${endpoint}`, {
            method: 'DELETE',
            headers: headers()
        });
        return handleResponse(res);
    },
    patch: async <T = any>(endpoint: string, data: any): Promise<T> => {
        const res = await fetch(`${API_URL}${endpoint}`, {
            method: 'PATCH',
            headers: headers(),
            body: JSON.stringify(data)
        });
        return handleResponse(res);
    }
};
