import { NextResponse } from 'next/server';
import { AppError } from '@server/errors';
import { childLogger } from '@server/logger';
import { runRequestLifecycle } from '@server/logger/request';

export type RouteContext = { params: Promise<Record<string, string>> };

export type RouteHandler = (
  req: Request,
  context: RouteContext
) => Promise<NextResponse | Response>;

const log = childLogger('http.api');

export function withErrorHandler(handler: RouteHandler): RouteHandler {
  return async (req, context) => {
    return runRequestLifecycle(req, async () => {
      try {
        return await handler(req, context);
      } catch (err) {
        if (err instanceof AppError) {
          return NextResponse.json(err.toJSON(), { status: err.statusCode });
        }
        log.error({ err }, 'unhandled API error');
        return NextResponse.json(
          { error: 'Internal server error', code: 'INTERNAL_ERROR' },
          { status: 500 }
        );
      }
    });
  };
}
