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

export interface AppError extends Error {
  statusCode?: number;
  code?: string;
}

export function errorHandler(
  err: AppError,
  _req: Request,
  res: Response,
  _next: NextFunction
): void {
  const statusCode = err.statusCode || 500;
  const message = err.message || 'Internal Server Error';

  logger.error(
    {
      err,
      statusCode,
      code: err.code,
    },
    'Request error'
  );

  res.status(statusCode).json({
    success: false,
    error: err.code || 'INTERNAL_ERROR',
    message: statusCode === 500 ? 'Internal Server Error' : message,
  });
}
