/**
 * React hook for automatic API call metrics tracking.
 *
 * Wraps fetch calls to automatically record duration and status.
 */

import { useCallback } from 'react';
import { recordApiCall } from '../utils/metrics';

/**
 * Hook that provides a tracked fetch wrapper.
 *
 * Usage:
 * ```
 * const trackedFetch = useTrackedFetch();
 * const response = await trackedFetch('/api/endpoint');
 * ```
 *
 * @returns A wrapper around fetch that automatically tracks metrics
 */
export function useTrackedFetch(): (
  input: RequestInfo | URL,
  init?: RequestInit,
) => Promise<Response> {
  return useCallback(async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
    const startTime = performance.now();
    const urlStr = typeof input === 'string' ? input : input.toString();

    try {
      const response = await fetch(input, init);
      const duration = performance.now() - startTime;

      const method = init?.method || 'GET';
      recordApiCall(method, urlStr, response.status, duration);

      return response;
    } catch (error) {
      const duration = performance.now() - startTime;
      // Record failed requests too (500 status for network errors)
      recordApiCall(init?.method || 'GET', urlStr, 500, duration);
      throw error;
    }
  }, []);
}
