import type { Request, Response, NextFunction } from "express";
import { makeLogger } from "../lib/logger.js";
import { latencyHistogram } from "../lib/histogram.js";

const logger = makeLogger("http");

export function responseTimeMiddleware(req: Request, res: Response, next: NextFunction): void {
  const startedAt = Date.now();

  res.on("finish", () => {
    const durationMs = Date.now() - startedAt;
    const route = req.route?.path as string | undefined;
    const routeKey = `${req.method} ${route ?? req.path}`;

    latencyHistogram.record(routeKey, durationMs);

    logger.info("request", {
      method:      req.method,
      path:        req.path,
      route:       route ?? null,
      status:      res.statusCode,
      duration_ms: durationMs,
      ip:
        (req.headers["x-forwarded-for"] as string | undefined)?.split(",")[0]?.trim() ??
        req.socket.remoteAddress ??
        null,
    });
  });

  next();
}
