// http/error-handler.ts
import type { MiddlewareHandler } from 'hono';
import { logger } from '../logger';
import { unexpectedProblem } from './problem-builders';

export const errorHandler: MiddlewareHandler = async (c, next) => {
  try {
    await next();
  } catch (error) {
    const requestId = c.get('requestId') as string | undefined;
    const instance = requestId ? `/requests/${requestId}` : undefined;

    logger.error({
      requestId,
      error,
    });

    return c.json(unexpectedProblem({ instance }), 500);
  }
};
