"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createHttpLoggingMiddleware = createHttpLoggingMiddleware;
function shouldSkipHttpLogging(url) {
    const path = url.split('?')[0] ?? url;
    return (path === '/docs' ||
        path.startsWith('/docs/') ||
        path === '/docs-json' ||
        path.startsWith('/docs-json/') ||
        path.includes('swagger-ui'));
}
function safeSerialize(payload) {
    try {
        const seen = new WeakSet();
        return JSON.stringify(payload, (_key, value) => {
            if (typeof value === 'bigint') {
                return value.toString();
            }
            if (typeof value === 'object' && value !== null) {
                if (seen.has(value)) {
                    return '[circular]';
                }
                seen.add(value);
            }
            return value;
        });
    }
    catch {
        return '[unserializable]';
    }
}
function createHttpLoggingMiddleware(loggerName, log) {
    return (req, res, next) => {
        const startedAt = Date.now();
        const method = req.method ?? 'UNKNOWN';
        const url = req.originalUrl ?? '/';
        if (shouldSkipHttpLogging(url)) {
            next();
            return;
        }
        const originalJson = res.json.bind(res);
        const originalSend = res.send.bind(res);
        let responsePayload;
        res.json = (body) => {
            responsePayload = body;
            return originalJson(body);
        };
        res.send = (body) => {
            responsePayload = body;
            return originalSend(body);
        };
        const requestPayload = {
            logger: loggerName,
            method,
            url,
            headers: req.headers,
            params: req.params,
            query: req.query,
            body: req.body
        };
        log(`[REQ] ${safeSerialize(requestPayload)}`);
        res.on('finish', () => {
            const responseLog = {
                logger: loggerName,
                method,
                url,
                statusCode: res.statusCode,
                durationMs: Date.now() - startedAt,
                body: responsePayload
            };
            log(`[RES] ${safeSerialize(responseLog)}`);
        });
        next();
    };
}
//# sourceMappingURL=http-logging.js.map