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

export const dynamic = "force-dynamic";

const CACHE_HEADERS = {
  "Cache-Control": "private, max-age=30, stale-while-revalidate=120",
};

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

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  // `range` honoured here for consistency with the other sub-tabs.
  // Default stays at "recent" (7 days) for the isNew / recentlyChanged
  // flags so users see what's changed recently even when the page
  // bundle covers 90d.
  const range = searchParams.get("range") || "30d";

  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 sevenDaysAgo = new Date(Date.now() - 7 * 86400000);

  try {
  // Parallelise the 3 independent reads (pages, SEO snapshots,
  // latest nav snapshot). Previously sequential; this drops cold-
  // pool wall time from sum-of-3 to max-of-3.
  const [pages, snapshots, latestNav] = await Promise.all([
    prisma.pageRecord.findMany({
      where: { brandId },
      select: {
        url: true, title: true, metaDescription: true, canonicalUrl: true, h1: true,
        firstSeenAt: true, lastSeenAt: true, currentStatus: true, isInNav: true,
        totalVisits: true, internalLinks: true,
      },
      orderBy: { lastSeenAt: "desc" },
      take: 200,
    }),
    prisma.pageSEOSnapshot.findMany({
      where: { brandId },
      select: {
        pageUrl: true, title: true, metaDescription: true, canonical: true,
        h1Count: true, hasSchema: true, schemaTypes: true, noindexed: true,
        mixedContent: true, detectedAt: true,
      },
      orderBy: { detectedAt: "desc" },
      take: 100,
    }),
    prisma.navSnapshot.findFirst({
      where: { brandId },
      orderBy: { capturedAt: "desc" },
      select: { links: true, capturedAt: true },
    }),
  ]);

  const pageDiscovery = pages.map(p => ({
    url: p.url,
    firstSeen: p.firstSeenAt.toISOString(),
    lastSeen: p.lastSeenAt.toISOString(),
    hasTitle: !!p.title,
    hasMeta: !!p.metaDescription,
    hasCanonical: !!p.canonicalUrl,
    hasH1: !!p.h1,
    isNew: p.firstSeenAt >= sevenDaysAgo,
    status: p.currentStatus,
    visits: p.totalVisits,
  }));

  // SEO snapshots aggregation (snapshots were fetched above in the
  // Promise.all parallel batch).
  const seoSnapshots = snapshots.map(s => ({
    url: s.pageUrl,
    title: s.title,
    metaDescription: s.metaDescription ? s.metaDescription.slice(0, 120) + (s.metaDescription.length > 120 ? "..." : "") : null,
    canonical: s.canonical,
    h1Count: s.h1Count,
    hasSchema: s.hasSchema,
    schemaTypes: s.schemaTypes as string[] | null,
    noindexed: s.noindexed,
    mixedContent: s.mixedContent,
    detectedAt: s.detectedAt.toISOString(),
    recentlyChanged: s.detectedAt >= sevenDaysAgo,
  }));

  // Nav structure aggregation (latestNav was fetched above in the
  // Promise.all parallel batch).

  // Internal link counts
  const internalLinks = pages.map(p => {
    const links = (p.internalLinks as Array<{ href: string }>) || [];
    return { url: p.url, outbound: links.length, isInNav: p.isInNav };
  });

  // Compute inbound counts
  const inboundMap: Record<string, number> = {};
  for (const p of pages) {
    const links = (p.internalLinks as Array<{ href: string }>) || [];
    for (const l of links) {
      inboundMap[l.href] = (inboundMap[l.href] || 0) + 1;
    }
  }
  const linkData = internalLinks.map(p => ({
    ...p,
    inbound: inboundMap[p.url] || 0,
    isOrphan: !p.isInNav && !(inboundMap[p.url]),
  })).sort((a, b) => a.inbound - b.inbound);

  const elapsed = Date.now() - t0;
  console.info("[site-tag-analytics:seo] query completed", { elapsed, pages: pages.length, snapshots: snapshots.length, range, brandId });

  return NextResponse.json({
    totalPages: pages.length,
    newPages: pageDiscovery.filter(p => p.isNew).length,
    pageDiscovery: pageDiscovery.slice(0, 100),
    seoSnapshots: seoSnapshots.slice(0, 50),
    navStructure: latestNav ? { links: latestNav.links, capturedAt: latestNav.capturedAt.toISOString() } : null,
    internalLinks: linkData.slice(0, 50),
  }, { headers: CACHE_HEADERS });
  } catch (err) {
    const elapsed = Date.now() - t0;
    console.error("[site-tag-analytics:seo] failed", { elapsed, range, brandId, err: err instanceof Error ? err.message : "unknown" });
    return NextResponse.json({ totalPages: 0, newPages: 0, pageDiscovery: [], seoSnapshots: [], navStructure: null, internalLinks: [] });
  }
}
