import useSWR from 'swr';
import { apiFetch } from './apiutils';

// Fetcher wrapper that uses our existing apiFetch
const fetcher = async (path: string) => {
    const res = await apiFetch(path);
    if (!res.ok) {
        const error = new Error('An error occurred while fetching the data.');
        // Attach extra info to the error object.
        (error as any).info = await res.json();
        (error as any).status = res.status;
        throw error;
    }
    return res.json();
};

export function useApi<T = any>(path: string | null) {
    const { data, error, isLoading, mutate } = useSWR<T>(path, fetcher, {
        // Optimistic settings for slow networks
        revalidateOnFocus: false, // Don't revalidate on window focus (saves inputs)
        dedupingInterval: 2000,   // Cache for 2 seconds before checking again
        keepPreviousData: true,   // Keep showing old data while fetching new
    });

    return {
        data,
        error,
        isLoading,
        mutate,
    };
}
