/**
 * GET /api/backlinks/top-pages?brandId=X — pages with most backlinks.
 */
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 brandId = new URL(req.url).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) 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 });

  const grouped = await prisma.backlink.groupBy({
    by: ["targetUrl"],
    where: { brandId, status: { in: ["active", "new"] } },
    _count: { id: true },
    orderBy: { _count: { id: "desc" } },
    take: 20,
  });

  const pages = await Promise.all(grouped.map(async (g) => {
    const domains = await prisma.backlink.groupBy({ by: ["sourceDomain"], where: { brandId, targetUrl: g.targetUrl, status: { in: ["active", "new"] } } });
    const avgDa = await prisma.backlink.aggregate({ where: { brandId, targetUrl: g.targetUrl, domainAuthority: { not: null } }, _avg: { domainAuthority: true } });
    return { targetUrl: g.targetUrl, backlinkCount: g._count.id, domainCount: domains.length, avgAuthority: Math.round((avgDa._avg.domainAuthority ?? 0) * 10) / 10 };
  }));

  return NextResponse.json({ pages });
}
