import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getCurrentUser } from "@/lib/auth";
import { verifyBrandAccess } from "@/lib/brand-access";
import { scoreBand, scoreBandLabel } from "@/lib/predictive-scoring/score-session";

export const dynamic = "force-dynamic";

// GET /api/dashboard/live-sessions?brandId=xxx&windowMinutes=30
export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  if (!(await verifyBrandAccess(user.id, brandId, req))) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const windowMinutes = Math.min(
    parseInt(searchParams.get("windowMinutes") ?? "30", 10) || 30,
    60,
  );

  const trackedSite = await prisma.trackedSite.findFirst({
    where: { brandId },
    select: { id: true },
  });
  if (!trackedSite) return NextResponse.json({ sessions: [], summary: null });

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

  const sessions = await prisma.trackedSession.findMany({
    where: {
      trackedSiteId: trackedSite.id,
      lastSeenAt: { gte: since },
    },
    select: {
      sessionId: true,
      entryPage: true,
      referrer: true,
      device: true,
      country: true,
      channelGroup: true,
      predictedConversionScore: true,
      scoreContributingFactors: true,
      startedAt: true,
      lastSeenAt: true,
      pageCount: true,
    },
    orderBy: { lastSeenAt: "desc" },
    take: 100,
  });

  const enriched = sessions.map((s) => {
    const score = s.predictedConversionScore ?? 0;
    const band = scoreBand(score);
    return {
      sessionId: s.sessionId,
      entryPage: s.entryPage,
      referrer: s.referrer,
      device: s.device,
      country: s.country,
      channelGroup: s.channelGroup,
      score,
      scoreBand: band,
      scoreBandLabel: scoreBandLabel(band),
      topFactors: (Array.isArray(s.scoreContributingFactors)
        ? (s.scoreContributingFactors as Array<{ signal: string; weight: number; source: string }>)
            .filter((f) => f.weight > 0)
            .sort((a, b) => b.weight - a.weight)
            .slice(0, 3)
            .map((f) => f.signal)
        : []),
      startedAt: s.startedAt,
      lastSeenAt: s.lastSeenAt,
      pageCount: s.pageCount,
      ageSeconds: Math.round((Date.now() - s.startedAt.getTime()) / 1000),
    };
  });

  const highIntent = enriched.filter((s) => s.score >= 61);
  const avgScore = enriched.length > 0
    ? Math.round(enriched.reduce((sum, s) => sum + s.score, 0) / enriched.length)
    : 0;

  return NextResponse.json({
    sessions: enriched,
    summary: {
      total: enriched.length,
      highIntent: highIntent.length,
      avgScore,
      windowMinutes,
    },
  });
}
