// middleware/errorHandler.ts
import { Request, Response, NextFunction } from "express";
import { HttpError, InternalServerError } from "../errors/httpErrors.js";

/**
 * Express global error-handling middleware.
 *
 * Responsibilities:
 * - Catch and handle errors thrown in controllers or routes
 * - Map known HttpError subclasses (ValidationError, UnauthorizedError, etc.)
 *   to the appropriate HTTP status code and JSON response
 * - Fallback to InternalServerError for unexpected/unhandled errors
 *
 * Usage:
 * 1. Register after all routes: `app.use(errorHandler);`
 * 2. Throw `HttpError` subclasses in your controllers/services
 * 3. Any other uncaught error is logged and returned as 500 Internal Server Error
 */
export function errorHandler(
  err: any,
  req: Request,
  res: Response,
  next: NextFunction
) {
  if (err instanceof HttpError) {
    return res.status(err.statusCode).json({ statusCode: err.statusCode, error: err.message });
  }

  console.error("Unexpected error:", err);

  const internalError = new InternalServerError(
    "An unexpected error occurred. Please try again later."
  );
  return res.status(internalError.statusCode).json({ error: internalError.message });
}
