"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AppError = void 0;
exports.errorHandler = errorHandler;
const zod_1 = require("zod");
const logger_1 = require("../utils/logger");
const env_1 = require("../config/env");
class AppError extends Error {
    statusCode;
    code;
    constructor(statusCode, message, code) {
        super(message);
        this.statusCode = statusCode;
        this.code = code;
        this.name = 'AppError';
    }
}
exports.AppError = AppError;
function errorHandler(err, _req, res, _next) {
    if (err instanceof AppError) {
        res.status(err.statusCode).json({
            error: {
                message: err.message,
                code: err.code,
            },
        });
        return;
    }
    if (err instanceof zod_1.ZodError) {
        const fieldErrors = err.flatten().fieldErrors;
        const errorCount = Object.keys(fieldErrors).length;
        res.status(400).json({
            error: {
                message: 'Validation error',
                code: 'VALIDATION_ERROR',
                // Only expose details in development
                ...(env_1.env.NODE_ENV === 'development' && { details: fieldErrors }),
                // In production, only show count
                ...(env_1.env.NODE_ENV === 'production' && { fieldCount: errorCount }),
            },
        });
        return;
    }
    logger_1.logger.error('Unhandled error:', err);
    res.status(500).json({
        error: {
            message: env_1.env.NODE_ENV === 'production' ? 'Internal server error' : err.message,
            code: 'INTERNAL_ERROR',
        },
    });
}
//# sourceMappingURL=error-handler.js.map