import { NextRequest, NextResponse } from 'next/server';
import { recordHttpRequest } from './metrics';

type RouteHandler = (
  request: NextRequest,
  context?: { params: Record<string, string> }
) => Promise<NextResponse> | NextResponse;

/**
 * Wrapper pour les routes API qui enregistre automatiquement les métriques HTTP
 *
 * Usage:
 * ```ts
 * import { withMetrics } from '@/lib/api-metrics';
 *
 * export const GET = withMetrics(async (request) => {
 *   return NextResponse.json({ data: 'hello' });
 * });
 * ```
 */
export function withMetrics(handler: RouteHandler): RouteHandler {
  return async (request: NextRequest, context?: { params: Record<string, string> }) => {
    const startTime = Date.now();
    const method = request.method;
    const path = new URL(request.url).pathname;

    try {
      const response = await handler(request, context);
      const duration = Date.now() - startTime;

      recordHttpRequest(method, path, response.status, duration);

      return response;
    } catch (error) {
      const duration = Date.now() - startTime;

      // Enregistrer comme erreur 500
      recordHttpRequest(method, path, 500, duration);

      throw error;
    }
  };
}

/**
 * Fonction pour enregistrer manuellement une métrique HTTP
 * Utile pour les cas où withMetrics ne peut pas être utilisé
 */
export { recordHttpRequest } from './metrics';
