/**
 * GET /api/backlinks/summary?brandId=X
 */
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 d30 = new Date(Date.now() - 30 * 86400000);
  const activeWhere = { brandId, status: { in: ["active", "new"] } };

  // Bucket ranges mirror the canonical 5-tier ladder in
  // src/lib/services/backlink-toxicity.ts — keep them in lockstep so
  // the page's health bar matches what the scorer writes.
  const [total, domains, newMonth, lostMonth, avgDa, quality,
    healthy, lowRisk, moderate, highRisk, toxic] = await Promise.all([
    prisma.backlink.count({ where: activeWhere }),
    prisma.backlink.groupBy({ by: ["sourceDomain"], where: activeWhere }),
    prisma.backlink.count({ where: { brandId, status: "new", firstSeenAt: { gte: d30 } } }),
    prisma.backlink.count({ where: { brandId, status: "lost", lostAt: { gte: d30 } } }),
    prisma.backlink.aggregate({ where: { brandId, domainAuthority: { not: null } }, _avg: { domainAuthority: true } }),
    prisma.backlink.groupBy({ by: ["qualityTier"], where: { brandId, qualityTier: { not: null } }, _count: true }),
    // Healthy ≤ 19 (or null score — treated as unknown but not flagged).
    prisma.backlink.count({ where: { ...activeWhere, OR: [{ toxicityScore: { lte: 19 } }, { toxicityScore: null }] } }),
    prisma.backlink.count({ where: { ...activeWhere, toxicityScore: { gte: 20, lt: 40 } } }),
    prisma.backlink.count({ where: { ...activeWhere, toxicityScore: { gte: 40, lt: 60 } } }),
    prisma.backlink.count({ where: { ...activeWhere, toxicityScore: { gte: 60, lt: 80 } } }),
    prisma.backlink.count({ where: { ...activeWhere, toxicityScore: { gte: 80 } } }),
  ]);

  return NextResponse.json({
    total, totalDomains: domains.length, newThisMonth: newMonth, lostThisMonth: lostMonth,
    avgDomainAuthority: Math.round((avgDa._avg.domainAuthority ?? 0) * 10) / 10,
    // toxicCount retained for backwards compatibility with OverviewCards —
    // High Risk + Toxic together match the legacy `>= 60` threshold.
    toxicCount: highRisk + toxic,
    qualityDistribution: Object.fromEntries(quality.map((q) => [q.qualityTier!, q._count])),
    health: { healthy, lowRisk, moderate, highRisk, toxic },
  });
}
