/**
 * GET /api/admin/ai-attribution-audit?brandId=…
 *
 * Returns every AiAttribution record for a brand with full detail,
 * cross-referenced against the original TrackedSession and any
 * SiteConversion records on the same session. Designed for data
 * accuracy auditing — not customer-facing.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin } from "@/lib/admin-auth";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const attributions = await prisma.aiAttribution.findMany({
    where: { brandId },
    orderBy: { timestamp: "desc" },
    take: 200,
  });

  const sessionIds = [...new Set(attributions.map((a) => a.sessionId))];

  const [sessions, conversions, allReferrerDomains] = await Promise.all([
    prisma.trackedSession.findMany({
      where: { sessionId: { in: sessionIds } },
      select: {
        id: true,
        sessionId: true,
        referrer: true,
        entryPage: true,
        startedAt: true,
        pageCount: true,
        userAgent: true,
        device: true,
        country: true,
        browser: true,
        os: true,
      },
    }),

    // intentionally unfiltered: admin-only endpoint; needs raw or all-time counts
    prisma.siteConversion.findMany({
      where: { brandId, sessionId: { in: sessionIds } },
      select: {
        id: true,
        sessionId: true,
        conversionType: true,
        pageUrl: true,
        timestamp: true,
      },
    }),

    prisma.trackedSession.findMany({
      where: {
        trackedSite: { brandId },
        referrer: { not: null },
      },
      select: { referrer: true },
      distinct: ["referrer"],
      take: 500,
    }),
  ]);

  const sessionMap = new Map(sessions.map((s) => [s.sessionId, s]));
  const convMap = new Map<string, typeof conversions>();
  for (const c of conversions) {
    const list = convMap.get(c.sessionId) ?? [];
    list.push(c);
    convMap.set(c.sessionId, list);
  }

  const BOT_PATTERNS = /bot|crawl|spider|scrape|headless|phantom|puppeteer|lighthouse|pagespeed|prerender/i;

  const detailed = attributions.map((a) => {
    const session = sessionMap.get(a.sessionId);
    const sessionConversions = convMap.get(a.sessionId) ?? [];
    const isSuspectedBot = session?.userAgent ? BOT_PATTERNS.test(session.userAgent) : false;

    let validationStatus: "verified" | "suspicious" | "unverifiable" = "unverifiable";
    let validationNote = "";

    if (!session) {
      validationNote = "Original TrackedSession not found — may have been purged.";
    } else if (isSuspectedBot) {
      validationStatus = "suspicious";
      validationNote = `User-Agent matches bot pattern: ${session.userAgent?.slice(0, 100)}`;
    } else if (a.aiPlatform === "google_ai_overview") {
      validationStatus = a.queryContext ? "verified" : "suspicious";
      validationNote = a.queryContext
        ? `Text fragment detected: "${a.queryContext.slice(0, 80)}"`
        : "No text fragment found — classified by heuristic only.";
    } else if (session.referrer) {
      const ref = session.referrer.toLowerCase();
      const platformInRef =
        (a.aiPlatform === "chatgpt" && (ref.includes("chatgpt.com") || ref.includes("chat.openai.com"))) ||
        (a.aiPlatform === "perplexity" && ref.includes("perplexity.ai")) ||
        (a.aiPlatform === "claude" && ref.includes("claude.ai")) ||
        (a.aiPlatform === "gemini" && ref.includes("gemini.google.com")) ||
        (a.aiPlatform === "copilot" && (ref.includes("copilot.microsoft.com") || ref.includes("bing.com/chat"))) ||
        (a.aiPlatform === "meta_ai" && ref.includes("meta.ai"));
      validationStatus = platformInRef ? "verified" : "suspicious";
      validationNote = platformInRef
        ? `Referrer confirmed: ${session.referrer.slice(0, 200)}`
        : `Referrer mismatch: expected ${a.aiPlatform} domain, got: ${session.referrer.slice(0, 200)}`;
    }

    return {
      id: a.id,
      sessionId: a.sessionId,
      aiPlatform: a.aiPlatform,
      channel: a.channel,
      referrerUrl: a.referrerUrl,
      queryContext: a.queryContext,
      landingPage: a.landingPage,
      timestamp: a.timestamp,
      converted: a.converted,
      conversionType: a.conversionType,
      pagesViewed: a.pagesViewed,
      engagementScore: a.engagementScore,
      validation: {
        status: validationStatus,
        note: validationNote,
        isSuspectedBot,
      },
      originalSession: session ? {
        referrer: session.referrer,
        entryPage: session.entryPage,
        pageCount: session.pageCount,
        userAgent: session.userAgent,
        device: session.device,
        browser: session.browser,
        os: session.os,
        country: session.country,
      } : null,
      conversionsInSession: sessionConversions,
    };
  });

  const referrerDomains = new Map<string, number>();
  for (const s of allReferrerDomains) {
    if (!s.referrer) continue;
    try {
      const host = new URL(s.referrer).hostname.replace(/^www\./, "");
      referrerDomains.set(host, (referrerDomains.get(host) ?? 0) + 1);
    } catch { /* skip */ }
  }
  const aiRelatedDomains = [...referrerDomains.entries()]
    .filter(([domain]) =>
      /chat|gpt|openai|perplexity|claude|gemini|bard|copilot|bing.*chat|meta\.ai|you\.com|phind|poe|ai/i.test(domain),
    )
    .sort((a, b) => b[1] - a[1]);

  const summary = {
    total: attributions.length,
    verified: detailed.filter((d) => d.validation.status === "verified").length,
    suspicious: detailed.filter((d) => d.validation.status === "suspicious").length,
    unverifiable: detailed.filter((d) => d.validation.status === "unverifiable").length,
    suspectedBots: detailed.filter((d) => d.validation.isSuspectedBot).length,
    withConversions: detailed.filter((d) => d.conversionsInSession.length > 0).length,
    conversionsMissingLink: detailed.filter((d) => !d.converted && d.conversionsInSession.length > 0).length,
    byPlatform: {} as Record<string, { total: number; verified: number; suspicious: number }>,
  };

  for (const d of detailed) {
    const plat = d.aiPlatform ?? "unknown";
    const entry = summary.byPlatform[plat] ?? { total: 0, verified: 0, suspicious: 0 };
    entry.total++;
    if (d.validation.status === "verified") entry.verified++;
    if (d.validation.status === "suspicious") entry.suspicious++;
    summary.byPlatform[plat] = entry;
  }

  return NextResponse.json({
    brandId,
    summary,
    attributions: detailed,
    aiRelatedReferrerDomains: aiRelatedDomains,
  });
}
