
export const API_BASE = '/api';

export function apiUrl(path: string): string {
    // Ensure path starts with /
    const normalizedPath = path.startsWith('/') ? path : `/${path}`;
    return `${API_BASE}${normalizedPath}`;
}

export async function apiFetch<T = any>(
    path: string,
    options: RequestInit = {}
): Promise<T> {
    const url = apiUrl(path);
    const response = await fetch(url, {
        ...options,
        headers: {
            'Content-Type': 'application/json',
            ...options.headers,
        },
    });
    
    if (!response.ok) {
        throw new Error(`API Error: ${response.status} ${response.statusText}`);
    }
    
    return response.json();
}


export async function apiGet<T = any>(path: string): Promise<T> {
    return apiFetch<T>(path, { method: 'GET' });
}


export async function apiPost<T = any>(path: string, body: any): Promise<T> {
    return apiFetch<T>(path, {
        method: 'POST',
        body: JSON.stringify(body),
    });
}

export async function apiPut<T = any>(path: string, body: any): Promise<T> {
    return apiFetch<T>(path, {
        method: 'PUT',
        body: JSON.stringify(body),
    });
}

export function reportViewUrl(filename: string): string {
    return `${API_BASE}/reports/view/${encodeURIComponent(filename)}`;
}
