/**
 * GET /api/performance-audit/history?brandId=xxx&limit=20
 *
 * Returns a chronological list of the brand's completed PerformanceAudit
 * runs, each with its site-wide average performance score + a handful
 * of supporting aggregates. Drives the "Performance over time" sparkline
 * on the Core Web Intelligence page so users can see whether their CWV
 * numbers are improving or regressing run-over-run.
 *
 * Cheap query — one findMany on PerformanceAudit (indexed by brandId)
 * + one aggregate per audit via the included pages relation. 20-point
 * default is enough for a 6-month history at weekly cadence.
 */

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

export const dynamic = "force-dynamic";

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");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  // Clamp to a sane ceiling — rendering 500 points on a sparkline is
  // pointless and enumerates the DB too aggressively.
  const limit = Math.min(50, Math.max(1, parseInt(searchParams.get("limit") ?? "20", 10) || 20));

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

  // Pull completed audits newest-first, flip to chronological order
  // before returning so the client can feed the array straight into
  // a left-to-right sparkline without reversing.
  const audits = await prisma.performanceAudit.findMany({
    where: { brandId, status: "completed" },
    orderBy: { completedAt: "desc" },
    take: limit,
    include: { pages: true },
  });

  const points = audits
    .map((a) => {
      const mobile = a.pages.filter((p) => p.device === "mobile");
      const desktop = a.pages.filter((p) => p.device === "desktop");
      const avg = (rows: typeof mobile, key: keyof typeof mobile[number]) => {
        if (rows.length === 0) return 0;
        const total = rows.reduce((sum, r) => sum + (r[key] as number), 0);
        return Math.round(total / rows.length);
      };
      return {
        auditId:      a.id,
        completedAt:  (a.completedAt ?? a.createdAt).toISOString(),
        pagesScored:  a.pages.length,
        mobilePerf:   avg(mobile,  "performance"),
        desktopPerf:  avg(desktop, "performance"),
        mobileLcpMs:  avg(mobile,  "lcpMs"),
        mobileClsMs:  mobile.length > 0
          ? Math.round((mobile.reduce((s, r) => s + r.clsVal, 0) / mobile.length) * 1000)
          : 0, // stored as cls × 1000 so the client has an integer to chart
      };
    })
    .reverse();

  return NextResponse.json({ points });
}
