import { Request, Response, NextFunction } from "express";
import { HttpError } from "../api/errors/httpErrors.js";
import { logger } from "../utils/logger.js";
import { HttpStatusCode } from "../api/apiHelpers/HttpStatusCodes.js";

/**
 * Error logging and handling middleware
 * Must be placed AFTER all routes
 * Logs all errors and sends appropriate responses
 */
export const errorLoggerMiddleware = (
    err: Error,
    req: Request,
    res: Response,
    next: NextFunction
) => {
    // Determine status code
    const statusCode = err instanceof HttpError
        ? err.statusCode
        : HttpStatusCode.INTERNAL_SERVER_ERROR;

    // Log the error with full details
    const userId = req.currentUser?.id || "anonymous";
    const fullPath = req.baseUrl + req.path;
    const errorDetails = {
        method: req.method,
        path: fullPath,
        userId,
        statusCode,
        message: err.message,
        name: err.name,
    };

    if (statusCode >= HttpStatusCode.INTERNAL_SERVER_ERROR) {
        // Server errors - log with stack trace
        logger.error(`Server Error: ${JSON.stringify(errorDetails)}`, { stack: err.stack });
    } else if (statusCode >= HttpStatusCode.BAD_REQUEST) {
        // Client errors - log as warning without stack trace
        logger.warn(`Client Error: ${JSON.stringify(errorDetails)}`);
    }

    // Send error response to client
    res.status(statusCode).json({
        error: {
            message: err.message,
            status: statusCode,
            ...(process.env.NODE_ENV === "development" && { stack: err.stack }),
        },
    });
};