/**
 * Error Handler Middleware
 * Handles errors and provides consistent error responses
 */

function errorHandler(err, req, res, next) {
    console.error('Error:', err.message);

    const statusCode = err.statusCode || 500;
    const message = process.env.NODE_ENV === 'production' && statusCode === 500
        ? 'Internal server error'
        : err.message;

    res.status(statusCode).json({
        success: false,
        error: { code: err.code || 'INTERNAL_ERROR', message }
    });
}

class ApiError extends Error {
    constructor(statusCode, code, message) {
        super(message);
        this.statusCode = statusCode;
        this.code = code;
    }
}

module.exports = { errorHandler, ApiError };
