/**
 * GET /api/site-tag/analytics/ai-detection-log?brandId=…&limit=20
 *
 * Returns the last N session starts with their AI classification
 * reasoning — useful for debugging why specific sessions were or
 * weren't flagged as AI referrals.
 */

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

export const dynamic = "force-dynamic";

const AI_DOMAINS = [
  "chat.openai.com", "chatgpt.com", "perplexity.ai", "claude.ai",
  "gemini.google.com", "bard.google.com", "copilot.microsoft.com",
  "you.com", "phind.com", "meta.ai", "poe.com",
];

interface LogEntry {
  sessionId: string;
  timestamp: string;
  referrer: string | null;
  landingPage: string;
  classification: "ai_overview" | "ai_platform" | "organic" | "direct" | "other";
  platform: string | null;
  hasTextFragment: boolean;
  reason: string;
  attributed: boolean;
}

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const limit = Math.min(parseInt(searchParams.get("limit") ?? "20", 10) || 20, 100);
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const site = await prisma.trackedSite.findUnique({
    where: { brandId },
    select: { id: true },
  });
  if (!site) return NextResponse.json({ entries: [] });

  const sessions = await prisma.trackedSession.findMany({
    where: { trackedSiteId: site.id },
    orderBy: { startedAt: "desc" },
    take: limit,
    select: { id: true, sessionId: true, startedAt: true, referrer: true, entryPage: true },
  });

  if (sessions.length === 0) return NextResponse.json({ entries: [] });

  const sessionIds = sessions.map((s) => s.id);
  const sessionIdsExternal = sessions.map((s) => s.sessionId);

  const [firstEvents, attributions] = await Promise.all([
    prisma.trackedEvent.findMany({
      where: { sessionId: { in: sessionIds }, eventType: { in: ["session_start", "page_view"] } },
      select: { sessionId: true, metadata: true, pageUrl: true, timestamp: true },
      orderBy: { timestamp: "asc" },
    }).catch(() => []),
    prisma.aiAttribution.findMany({
      where: { brandId, sessionId: { in: sessionIdsExternal } },
      select: { sessionId: true },
    }).catch(() => []),
  ]);

  const firstEventBySession = new Map<string, { metadata: unknown; pageUrl: string | null }>();
  for (const ev of firstEvents) {
    if (!ev.sessionId) continue;
    if (!firstEventBySession.has(ev.sessionId)) {
      firstEventBySession.set(ev.sessionId, { metadata: ev.metadata, pageUrl: ev.pageUrl });
    }
  }

  const attributedSet = new Set(attributions.map((a) => a.sessionId));

  const entries: LogEntry[] = sessions.map((s) => {
    const ref = (s.referrer ?? "").toLowerCase();
    const firstEv = firstEventBySession.get(s.id);
    const meta = (firstEv?.metadata ?? {}) as Record<string, unknown>;
    const fragment = typeof meta.landingTextFragment === "string" && meta.landingTextFragment
      ? meta.landingTextFragment
      : (typeof meta.textFragment === "string" && meta.textFragment ? meta.textFragment : null);
    const hasTextFragment = !!fragment;

    let classification: LogEntry["classification"] = "other";
    let platform: string | null = null;
    let reason: string;

    if (!ref) {
      classification = "direct";
      reason = "No referrer — direct visit";
    } else {
      const matchedAi = AI_DOMAINS.find((d) => ref.includes(d));
      const isGoogle = /(^|\.)google\.[a-z.]+/.test(ref);
      const isBingChat = ref.includes("bing.com") && ref.includes("/chat");

      if (matchedAi) {
        classification = "ai_platform";
        platform = matchedAi;
        reason = `Referrer from ${matchedAi} — AI platform detected`;
      } else if (isBingChat) {
        classification = "ai_platform";
        platform = "bing.com/chat";
        reason = "Referrer from Bing Chat — AI platform detected";
      } else if (isGoogle && hasTextFragment) {
        classification = "ai_overview";
        platform = "google_ai_overview";
        reason = "Google referrer + text fragment — likely AI Overview click";
      } else if (isGoogle) {
        classification = "organic";
        reason = "Google referrer, no text fragment — likely organic";
      } else {
        classification = "other";
        reason = `Referrer: ${ref.slice(0, 60)} — not an AI platform`;
      }
    }

    return {
      sessionId: s.sessionId,
      timestamp: s.startedAt.toISOString(),
      referrer: s.referrer,
      landingPage: s.entryPage,
      classification,
      platform,
      hasTextFragment,
      reason,
      attributed: attributedSet.has(s.sessionId),
    };
  });

  return NextResponse.json({ entries });
}
