/**
 * Global Error Handler Middleware
 * 
 * Purpose: Catch all errors, log them, and return consistent error responses
 * Applied as the last middleware in the Express chain
 */

import { Request, Response, NextFunction } from 'express';
import { appConfig } from '../config/app';

export class AppError extends Error {
  constructor(
    public statusCode: number,
    public message: string,
    public isOperational = true
  ) {
    super(message);
    Object.setPrototypeOf(this, AppError.prototype);
  }
}

export function errorHandler(
  err: Error | AppError,
  req: Request,
  res: Response,
  next: NextFunction
): void {
  console.error('Error:', err);

  if (err instanceof AppError) {
    res.status(err.statusCode).json({
      success: false,
      error: err.message,
    });
    return;
  }

  // Unexpected errors
  res.status(500).json({
    success: false,
    error: appConfig.env === 'production' 
      ? 'Internal server error' 
      : err.message,
  });
}
