import type { NextRequest } from "next/server";
import { errorResponse } from "./response";

type Handler<TArgs extends any[]> = (...args: TArgs) => Promise<Response>;

export function withErrorHandling<TArgs extends any[]>(handler: Handler<TArgs>): Handler<TArgs> {
  return async (...args: TArgs) => {
    try {
      return await handler(...args);
    } catch (err) {
      // eslint-disable-next-line no-console
      console.error(err);
      return errorResponse(err);
    }
  };
}

// Utility type so route handlers can annotate args when they want.
export type RouteHandlerRequest = Request | NextRequest;
