/**
 * Prometheus HTTP metrics middleware for SentryAgent.ai AgentIdP.
 * Records request count and duration for every HTTP request.
 */
import { Request, Response, NextFunction } from 'express';
import { httpRequestsTotal, httpRequestDurationSeconds } from '../metrics/registry.js';

/**
 * Normalises an Express request path to a stable route label.
 * Replaces UUIDs and numeric IDs with ':id' to avoid high cardinality.
 *
 * @param req - The Express request object.
 * @returns A normalised route string.
 */
function normalisePath(req: Request): string {
  // Use matched route pattern if available (most accurate)
  const route = req.route?.path as string | undefined;
  if (route) {
    return `${req.baseUrl}${route}`;
  }
  // Fall back to original URL stripped of query, with UUIDs replaced
  return req.path.replace(
    /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
    ':id',
  );
}

/**
 * Express middleware that records Prometheus HTTP metrics for every request.
 * Must be registered BEFORE routes in app.ts.
 *
 * @param req - Express request.
 * @param res - Express response.
 * @param next - Express next function.
 */
export function metricsMiddleware(req: Request, res: Response, next: NextFunction): void {
  const startTime = Date.now();

  res.on('finish', () => {
    const route = normalisePath(req);
    const labels = {
      method: req.method,
      route,
      status_code: String(res.statusCode),
    };
    httpRequestsTotal.inc(labels);
    httpRequestDurationSeconds.observe(labels, (Date.now() - startTime) / 1000);
  });

  next();
}
