import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  getLatestAudit,
  buildStatsViewModel,
  type SiteTagStatCounts,
} from "@/app/technical-audit/_lib/queries";
import { getErrorPatterns } from "@/lib/services/site-tag-analytics";

export const dynamic = "force-dynamic";

const STATS_TIMEOUT_MS = 5000;

function timedCount(query: Promise<number>): Promise<number | null> {
  const timeout = new Promise<null>((resolve) => setTimeout(() => resolve(null), STATS_TIMEOUT_MS));
  return Promise.race([query, timeout]);
}

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ brandId: string }> },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { brandId } = await params;

  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 result = await getLatestAudit(brandId);
  if (!result) return NextResponse.json(null);

  const since30d = new Date(Date.now() - 30 * 86_400_000);
  const [jsErrCount, frictionCount, brokenCount, errorPatterns, frictionPages] =
    await Promise.all([
      timedCount(prisma.siteEvent.count({
        where: { brandId, eventType: "js_error", timestamp: { gte: since30d } },
      })).catch(() => null),
      timedCount(prisma.siteEvent.count({
        where: { brandId, eventType: { in: ["rage_click", "dead_click"] }, timestamp: { gte: since30d } },
      })).catch(() => null),
      timedCount(prisma.siteEvent.count({
        where: { brandId, eventType: { in: ["broken_link", "http_error"] }, timestamp: { gte: since30d } },
      })).catch(() => null),
      getErrorPatterns(brandId).catch(() => null),
      prisma.siteEvent.findMany({
        where: { brandId, eventType: { in: ["rage_click", "dead_click"] }, timestamp: { gte: since30d } },
        select: { pageUrl: true },
        distinct: ["pageUrl"],
        take: 200,
      }).then((rows) => rows.length).catch(() => null),
    ]);

  const siteTag: SiteTagStatCounts = {
    errors: jsErrCount,
    friction: frictionCount,
    notFound: brokenCount,
    errorPatterns,
    frictionPageCount: frictionPages,
  };

  const timedOut = jsErrCount === null || frictionCount === null || brokenCount === null;
  const statsStatus: "complete" | "partial" | "updating" = timedOut
    ? (jsErrCount === null && frictionCount === null && brokenCount === null ? "updating" : "partial")
    : "complete";

  return NextResponse.json({
    statsVm: buildStatsViewModel(result.seoSection, siteTag),
    statsStatus,
  });
}
