import { Env } from '../config/env.js';
import { Logger } from '../config/logger.js';
import { RequestContext } from '../http/RequestContext.js';
const getStatusSafe = (res) => {
    const anyRes = res;
    if (typeof anyRes.getStatus === 'function')
        return anyRes.getStatus();
    if (typeof anyRes.statusCode === 'number')
        return anyRes.statusCode;
    return 200;
};
export const LoggingMiddleware = Object.freeze({
    create(options = {}) {
        const enabled = typeof options.enabled === 'boolean' ? options.enabled : Boolean(Env.LOG_HTTP_REQUEST);
        return async (req, res, next) => {
            if (enabled === false) {
                await next();
                return;
            }
            const start = Date.now();
            const method = req.getMethod();
            const path = req.getPath();
            const ctx = RequestContext.get(req);
            const requestId = ctx?.requestId ?? req.context['requestId'];
            const traceId = ctx?.traceId;
            const prefix = typeof traceId === 'string' && traceId.trim() !== ''
                ? `[${requestId} trace=${traceId}]`
                : `[${requestId}]`;
            Logger.info(`${prefix} ↓ ${method} ${path}`);
            try {
                await next();
            }
            finally {
                const durationMs = Date.now() - start;
                const status = getStatusSafe(res);
                Logger.info(`${prefix} ↑ ${method} ${path} ${status} ${durationMs}ms`);
            }
        };
    },
});
export default LoggingMiddleware;
