import { NextResponse } from "next/server";
import { getSuperadmin } from "@/lib/admin-auth";
import { prisma } from "@/lib/prisma";
import { scoreSession } from "@/lib/predictive-scoring/score-session";

// POST /api/site-tag/recompute-scores
// Admin-only: batch recompute predictive conversion scores for recent sessions.
export async function POST(req: Request) {
  const admin = await getSuperadmin();
  if (!admin) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

  const body = await req.json().catch(() => ({}));
  const windowHours: number = typeof body.windowHours === "number" ? body.windowHours : 24;
  const brandId: string | undefined = typeof body.brandId === "string" ? body.brandId : undefined;

  const since = new Date(Date.now() - windowHours * 60 * 60 * 1000);

  // Resolve trackedSiteIds for the brand filter
  let trackedSiteIds: string[] | undefined;
  if (brandId) {
    const site = await prisma.trackedSite.findFirst({
      where: { brandId },
      select: { id: true },
    });
    if (!site) return NextResponse.json({ error: "Brand has no tracked site" }, { status: 404 });
    trackedSiteIds = [site.id];
  }

  const sessions = await prisma.trackedSession.findMany({
    where: {
      startedAt: { gte: since },
      ...(trackedSiteIds ? { trackedSiteId: { in: trackedSiteIds } } : {}),
    },
    take: 500,
  });

  let updated = 0;
  let failed = 0;

  for (const session of sessions) {
    try {
      const [recentEvents, heatmapEvents] = await Promise.all([
        prisma.siteEvent.findMany({
          where: { sessionId: session.sessionId },
          select: { eventType: true, eventData: true, timestamp: true },
          orderBy: { timestamp: "desc" },
          take: 50,
        }),
        prisma.heatmapEvent.findMany({
          where: { sessionId: session.sessionId },
          select: { pageUrl: true, timeOnPage: true, maxScrollPercent: true },
          take: 20,
        }),
      ]);

      const pageVisits = heatmapEvents.map((h) => ({
        pageUrl: h.pageUrl,
        timeOnPage: h.timeOnPage ?? undefined,
        maxScrollPercent: h.maxScrollPercent ?? undefined,
      }));

      const { score, contributingFactors } = scoreSession(
        session,
        recentEvents as Parameters<typeof scoreSession>[1],
        pageVisits,
      );

      await prisma.trackedSession.update({
        where: { id: session.id },
        data: {
          predictedConversionScore: score,
          scoreLastComputedAt: new Date(),
          scoreContributingFactors: contributingFactors as object[],
        },
      });
      updated++;
    } catch {
      failed++;
    }
  }

  return NextResponse.json({ updated, failed, sessionsProcessed: sessions.length });
}
