import { throwError } from "rxjs";
import { catchError } from "rxjs/operators";
import error_tracking from "./error-tracking/index.mjs";
function getClientIp(headers, request) {
    const forwarded = headers['x-forwarded-for'];
    if (forwarded) {
        const ip = String(forwarded).split(',')[0].trim();
        if (ip) return ip;
    }
    return request?.socket?.remoteAddress;
}
function getExceptionStatus(exception) {
    if (exception && 'object' == typeof exception && 'getStatus' in exception && 'function' == typeof exception.getStatus) {
        const status = exception.getStatus();
        return 'number' == typeof status ? status : void 0;
    }
}
class PostHogInterceptor {
    constructor(posthog, options){
        this.posthog = posthog;
        const capture = options?.captureExceptions;
        this.captureExceptions = !!capture;
        this.minStatusToCapture = ('object' == typeof capture ? capture.minStatusToCapture : void 0) ?? 500;
    }
    intercept(context, next) {
        const httpHost = context.switchToHttp();
        const request = httpHost.getRequest();
        const response = httpHost.getResponse();
        const headers = request?.headers ?? {};
        const sessionId = headers['x-posthog-session-id'];
        const windowId = headers['x-posthog-window-id'];
        const distinctId = headers['x-posthog-distinct-id'];
        const contextData = {
            sessionId,
            distinctId,
            properties: {
                $current_url: request?.url,
                $request_method: request?.method,
                $request_path: request?.path ?? request?.url,
                $window_id: windowId,
                $user_agent: headers['user-agent'],
                $ip: getClientIp(headers, request)
            }
        };
        this.posthog.enterContext(contextData);
        let source = next.handle();
        if (this.captureExceptions) source = source.pipe(catchError((exception)=>{
            if (error_tracking.isPreviouslyCapturedError(exception)) return throwError(()=>exception);
            const status = getExceptionStatus(exception);
            if (void 0 !== status && status < this.minStatusToCapture) return throwError(()=>exception);
            const responseStatus = status ?? response?.statusCode;
            const additionalProperties = void 0 !== responseStatus ? {
                $response_status_code: responseStatus
            } : void 0;
            this.posthog.captureException(exception, distinctId, additionalProperties);
            return throwError(()=>exception);
        }));
        return source;
    }
}
export { PostHogInterceptor };
