import { clearBrowserSessionState } from '../store/useAuthStore';

const API_BASE = import.meta.env.VITE_API_URL || '/api';

/**
 * Centralized API fetch wrapper that automatically attaches the auth token.
 */
export async function apiFetch<T = unknown>(
    path: string,
    options: RequestInit = {},
): Promise<T> {
    const token = localStorage.getItem('hipograf_token');
    const headers: Record<string, string> = {
        ...(options.headers as Record<string, string> || {}),
    };

    if (!(options.body instanceof FormData) && !headers['Content-Type']) {
        headers['Content-Type'] = 'application/json';
    }

    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    const res = await fetch(`${API_BASE}${path}`, {
        ...options,
        headers,
    });

    if (res.status === 401) {
        // Token expired or invalid – clear auth and reload
        clearBrowserSessionState();
        window.location.href = '/';
        throw new Error('Unauthorized');
    }

    if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || `API error ${res.status}`);
    }

    // Handle empty responses (like 204 No Content)
    if (res.status === 204) {
        return {} as T;
    }

    const text = await res.text();
    return text ? JSON.parse(text) : {} as T;
}
