import { ZodError } from "zod";
import { HttpError } from "../errors.js";
import { trackErrorHandlerCrash } from "@zmeel/shared/telemetry";
import { getTelemetryClient } from "../telemetry.js";
function attachErrorContext(req, res, payload, rawError) {
    res.__errorContext = {
        error: payload,
        method: req.method,
        url: req.originalUrl,
        reqBody: req.body,
        reqParams: req.params,
        reqQuery: req.query,
    };
    if (rawError) {
        res.err = rawError;
    }
}
export function errorHandler(err, req, res, _next) {
    if (err instanceof HttpError) {
        if (err.status >= 500) {
            attachErrorContext(req, res, { message: err.message, stack: err.stack, name: err.name, details: err.details }, err);
            const tc = getTelemetryClient();
            if (tc)
                trackErrorHandlerCrash(tc, { errorCode: err.name });
        }
        res.status(err.status).json({
            error: err.message,
            ...(err.details ? { details: err.details } : {}),
        });
        return;
    }
    if (err instanceof ZodError) {
        res.status(400).json({ error: "Validation error", details: err.errors });
        return;
    }
    const rootError = err instanceof Error ? err : new Error(String(err));
    attachErrorContext(req, res, err instanceof Error
        ? { message: err.message, stack: err.stack, name: err.name }
        : { message: String(err), raw: err, stack: rootError.stack, name: rootError.name }, rootError);
    const tc = getTelemetryClient();
    if (tc)
        trackErrorHandlerCrash(tc, { errorCode: rootError.name });
    res.status(500).json({ error: "Internal server error" });
}
//# sourceMappingURL=error-handler.js.map