import error_tracking from "./error-tracking/index.mjs";
function setupExpressErrorHandler(_posthog, app) {
    app.use(posthogErrorHandler(_posthog));
}
function posthogErrorHandler(posthog) {
    return (error, req, res, next)=>{
        if (error_tracking.isPreviouslyCapturedError(error)) return void next(error);
        const sessionId = req.headers['x-posthog-session-id'];
        const distinctId = req.headers['x-posthog-distinct-id'];
        const syntheticException = new Error('Synthetic exception');
        const hint = {
            mechanism: {
                type: 'middleware',
                handled: false
            },
            syntheticException
        };
        posthog.addPendingPromise(error_tracking.buildEventMessage(error, hint, distinctId, {
            $session_id: sessionId,
            $current_url: req.url,
            $request_method: req.method,
            $request_path: req.path,
            $user_agent: req.headers['user-agent'],
            $response_status_code: res.statusCode,
            $ip: req.headers['x-forwarded-for'] || req?.socket?.remoteAddress
        }).then((msg)=>{
            posthog.capture(msg);
        }));
        next(error);
    };
}
export { setupExpressErrorHandler };
