import { NextResponse } from 'next/server';
import { AppError } from '@server/errors';

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

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

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