import { Request, Response, NextFunction } from 'express';
import { logger } from '../utils/logger';

export class AgentError extends Error {
  constructor(public statusCode: number, message: string, public code?: string) {
    super(message);
    this.name = 'AgentError';
  }
}

export function errorHandler(err: Error, _req: Request, res: Response, _next: NextFunction) {
  if (err instanceof AgentError) {
    res.status(err.statusCode).json({
      error: err.code || 'AGENT_ERROR',
      message: err.message,
    });
    return;
  }

  logger.error(`Unhandled error: ${err.message}`);
  res.status(500).json({
    error: 'INTERNAL_ERROR',
    message: 'An internal error occurred',
  });
}
