import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  try {
    const { visitorId, path } = await req.json();

    if (!visitorId || !path) {
      return NextResponse.json({ error: "Missing visitorId or path" }, { status: 400 });
    }

    // Try to find an existing session for this visitor within the last 30 minutes
    // If it exists, update it and add a page view. If not, create a new session.
    const thirtyMinutesAgo = new Date(Date.now() - 30 * 60 * 1000);

    let session = await prisma.session.findFirst({
      where: {
        visitorId,
        lastSeenAt: {
          gt: thirtyMinutesAgo,
        },
      },
      orderBy: { lastSeenAt: "desc" },
    });

    if (!session) {
      session = await prisma.session.create({
        data: {
          visitorId,
        },
      });
    } else {
      await prisma.session.update({
        where: { id: session.id },
        data: { lastSeenAt: new Date() },
      });
    }

    // Record the page view
    await prisma.pageView.create({
      data: {
        sessionId: session.id,
        path,
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Tracking error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
