import { Request, Response, NextFunction } from 'express';

export interface ErrorWithStatus extends Error {
  status?: number;
  statusCode?: number;
}

export const errorHandler = (
  err: ErrorWithStatus,
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  const status = err.status || err.statusCode || 500;
  const message = err.message || 'Internal Server Error';

  console.error('Error:', {
    status,
    message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
  });

  res.status(status).json({
    success: false,
    message: process.env.NODE_ENV === 'production' 
      ? (status === 500 ? 'Internal Server Error' : message)
      : message,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
  });
};