import { env, createLogger } from '@4runr/shared';
import { getCorrelationId } from './correlationId.js';
const logger = createLogger('Gateway:ErrorHandler');
function maskError(error, isProduction) {
    if (!isProduction) {
        return {
            error: error.name || 'Error',
            message: error.message,
            ...(error.stack && { stack: error.stack }),
        };
    }
    const statusCode = error.statusCode || 500;
    if (statusCode >= 500) {
        return {
            error: 'Internal Server Error',
            message: 'An unexpected error occurred. Please try again later.',
        };
    }
    return {
        error: error.name || 'Error',
        message: error.message,
    };
}
export function errorHandler(error, request, reply) {
    const isProduction = env.NODE_ENV === 'production';
    const correlationId = getCorrelationId(request);
    const statusCode = error.statusCode || 500;
    const maskedError = maskError(error, isProduction);
    const errorResponse = {
        error: maskedError.error || 'Error',
        message: maskedError.message || 'An error occurred',
        ...(correlationId && { correlationId }),
        timestamp: new Date().toISOString(),
        path: request.url,
        statusCode,
        ...(maskedError.stack && { stack: maskedError.stack }),
    };
    const route = request.routeOptions?.url || request.url.split('?')[0] || 'unknown';
    const method = request.method;
    if (statusCode >= 500) {
        logger.error('Server error', {
            correlationId,
            error: error.message,
            stack: error.stack,
            path: request.url,
            method,
            route,
            statusCode,
            userId: request.apiKey || request.user?.sub || 'anonymous',
        });
    }
    else {
        logger.warn('Client error', {
            correlationId,
            error: error.message,
            path: request.url,
            method,
            route,
            statusCode,
        });
    }
    reply.status(statusCode).send(errorResponse);
}
export function handleValidationError(error, request, reply) {
    const correlationId = getCorrelationId(request);
    logger.warn('Validation error', {
        correlationId,
        error: error.message,
        path: request.url,
        method: request.method,
    });
    const errorResponse = {
        error: 'Validation Error',
        message: error.message || 'Invalid request data',
        timestamp: new Date().toISOString(),
        path: request.url,
        statusCode: 400,
        ...(correlationId && { correlationId }),
    };
    reply.status(400).send(errorResponse);
}
export function handleNotFound(request, reply) {
    const correlationId = getCorrelationId(request);
    logger.debug('Route not found', {
        correlationId,
        path: request.url,
        method: request.method,
    });
    reply.status(404).send({
        error: 'Not Found',
        message: `Route ${request.method} ${request.url} not found`,
        correlationId,
        timestamp: new Date().toISOString(),
        path: request.url,
        statusCode: 404,
    });
}
//# sourceMappingURL=errorHandler.js.map