/**
 * GET /api/backlinks/referring-domains?brandId=X
 * Returns unique referring domains, either from DataForSEO or aggregated from DB.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { hasDataForSEO, fetchReferringDomains } from "@/lib/services/dataforseo-backlinks";

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 });
  }

  // Try DataForSEO first
  if (hasDataForSEO()) {
    const domains = await fetchReferringDomains(brand.domain, 200);
    if (domains.length > 0) {
      return NextResponse.json({
        domains: domains.map((d) => ({
          domain: d.domain,
          rank: d.rank,
          backlinks: d.backlinks,
          firstSeen: d.first_seen,
          lastSeen: d.last_seen,
        })),
        // Generic wire-format discriminator — keeps the SERP vendor
        // name out of any JSON response a user might inspect.
        source: "live",
      });
    }
  }

  // Fall back to aggregated DB data
  const grouped = await prisma.backlink.groupBy({
    by: ["sourceDomain"],
    where: { brandId, status: { in: ["active", "new"] } },
    _count: true,
    _avg: { domainAuthority: true },
    _min: { firstSeenAt: true },
    _max: { lastSeenAt: true },
    orderBy: { _count: { sourceDomain: "desc" } },
    take: 200,
  });

  return NextResponse.json({
    domains: grouped.map((g) => ({
      domain: g.sourceDomain,
      rank: Math.round((g._avg.domainAuthority ?? 0) * 10),
      backlinks: g._count,
      firstSeen: g._min.firstSeenAt,
      lastSeen: g._max.lastSeenAt,
    })),
    source: "database",
  });
}
