import Logger from "@/app/www/system/Logger";
import { NextRequest } from "next/server";

export default function logIP(
  route: (
    request: NextRequest,
    params: { params: Record<string, string> },
  ) => Promise<Response>,
) {
  return async (
    req: NextRequest,
    params: { params: Record<string, string> },
  ) => {
    if (!req.headers.has("X-Real-IP")) {
      req.headers.set("X-Real-IP", req.ip ?? "localhost");
    }

    try {
      const res = await route(req, params);
      Logger.info(
        `[${req.headers.get("X-Real-IP")}] ${req.method} ${req.nextUrl} ${res.status}`,
      );
      return res;
    } catch (e) {
      Logger.error(e);
      return new Response(undefined, { status: 500 });
    }
  };
}
