/**
 * Global Express error-handling middleware for SentryAgent.ai AgentIdP.
 * Maps SentryAgentError subclasses to their HTTP status codes and error shapes.
 * Unknown errors are mapped to 500 Internal Server Error.
 */

import { Request, Response, NextFunction } from 'express';
import { SentryAgentError } from '../utils/errors.js';
import { IErrorResponse } from '../types/index.js';

/**
 * Express error-handling middleware.
 * Must have exactly 4 parameters to be recognised as an error handler.
 *
 * @param err - The error thrown by a route handler or upstream middleware.
 * @param _req - Express request (unused).
 * @param res - Express response.
 * @param _next - Express next function (unused but required by Express signature).
 */
export function errorHandler(
  err: unknown,
  _req: Request,
  res: Response,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  _next: NextFunction,
): void {
  if (err instanceof SentryAgentError) {
    const body: IErrorResponse = {
      code: err.code,
      message: err.message,
    };
    if (err.details !== undefined) {
      body.details = err.details;
    }
    res.status(err.httpStatus).json(body);
    return;
  }

  // Unexpected error — log and return generic 500
  // eslint-disable-next-line no-console
  console.error('Unhandled error:', err);

  const body: IErrorResponse = {
    code: 'INTERNAL_SERVER_ERROR',
    message: 'An unexpected error occurred. Please try again later.',
  };
  res.status(500).json(body);
}
