/**
 * GET /api/client-portal/rankings?brandId=X
 * Client-facing rank tracking summary.
 */

import { NextResponse } from "next/server";
import { requireClientAuth, pageAllowed } from "@/lib/client-auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const brandId = new URL(req.url).searchParams.get("brandId") || "";
  const auth = await requireClientAuth(brandId);
  if (!auth.ok) return NextResponse.json({ error: auth.error }, { status: auth.status });
  if (!pageAllowed(auth.session, "rankings")) return NextResponse.json({ error: "Page not allowed" }, { status: 403 });

  const keywords = await prisma.trackedKeyword.findMany({
    where: { brandId, isActive: true },
    include: { rankings: { orderBy: { checkedAt: "desc" }, take: 1 } },
  });

  let sumPos = 0, withPos = 0, top3 = 0, top10 = 0;
  const rows = keywords.map((kw) => {
    const latest = kw.rankings[0];
    const pos = latest?.position ?? null;
    if (pos != null) { withPos++; sumPos += pos; if (pos <= 3) top3++; if (pos <= 10) top10++; }
    const change = pos != null && latest?.previousPosition != null ? latest.previousPosition - pos : null;
    return { keyword: kw.keyword, position: pos, change, url: latest?.url ?? null };
  });

  return NextResponse.json({
    total: keywords.length,
    avgPosition: withPos > 0 ? Math.round((sumPos / withPos) * 10) / 10 : null,
    top3, top10,
    keywords: rows,
  });
}
