import { NextResponse } from "next/server";
import { connectToDB } from "./app/lib/db";
import Visit from "./app/lib/models/visits"; // Correct the import to match the file name


export async function middleware(req: Request) {
  const ip =
    req.headers.get("x-forwarded-for") || req.headers.get("remote-addr") || "127.0.0.1";

  const { pathname } = new URL(req.url);

  if (pathname === "/" || pathname === "/submit-cv") {
    try {
      await fetch("http://localhost:3000/api/track-visit", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ip }),
      });
      console.log("Visit tracked:", ip);
    } catch (error) {
      console.error("Error sending visit to API:", error);
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/", "/submit-cv"],
};
