import { NextFunction, Request, Response } from "express";
import { logger } from "../services/logger";

function classifyLevel(statusCode: number) {
  if (statusCode >= 500) {
    return "error" as const;
  }
  if (statusCode >= 400) {
    return "warn" as const;
  }
  return "info" as const;
}

export function requestLogging(req: Request, res: Response, next: NextFunction) {
  const startedAt = process.hrtime.bigint();

  res.on("finish", () => {
    const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
    const level = classifyLevel(res.statusCode);
    logger[level]("http_request", {
      request_id: req.requestId,
      trace_id: req.traceId,
      method: req.method,
      path: req.originalUrl || req.url,
      status_code: res.statusCode,
      duration_ms: Number(durationMs.toFixed(2)),
      content_length: res.getHeader("content-length") || null,
      user_agent: req.header("user-agent") || null,
      ip: req.ip
    });
  });

  next();
}
