import type { Request, Response, NextFunction } from 'express';
import { createCorrelationContext, CORRELATION_ID_HEADER, REQUEST_ID_HEADER } from '@dbis/integration-foundation';
import { appendOmnlAudit } from '../../services/omnl-audit-log';

/** Attach trace/correlation ids and log every /omnl request (response status on finish). */
export function omnlAuditMiddleware(req: Request, res: Response, next: NextFunction): void {
  const ctx = createCorrelationContext({
    correlationId: String(req.headers[CORRELATION_ID_HEADER] ?? req.headers['x-omnl-trace-id'] ?? ''),
    requestId: String(req.headers[REQUEST_ID_HEADER] ?? ''),
  });
  req.headers[CORRELATION_ID_HEADER] = ctx.correlationId;
  req.headers['x-omnl-trace-id'] = ctx.correlationId;
  req.headers[REQUEST_ID_HEADER] = ctx.requestId;
  const traceId = ctx.correlationId;
  res.setHeader('X-OMNL-Trace-Id', traceId);
  res.setHeader(CORRELATION_ID_HEADER, ctx.correlationId);
  res.setHeader(REQUEST_ID_HEADER, ctx.requestId);
  const started = Date.now();
  res.on('finish', () => {
    appendOmnlAudit({
      category: 'api',
      action: `${req.method} ${req.path}`,
      actor: req.headers['x-omnl-actor'] as string | undefined,
      sourceSystem: (req.headers['x-omnl-source'] as string) || 'http',
      traceId,
      status: res.statusCode < 400 ? 'ok' : 'error',
      metadata: {
        statusCode: res.statusCode,
        durationMs: Date.now() - started,
        query: req.query,
      },
    });
  });
  next();
}
