/**
 * GET /api/backlinks?brandId=X&status=all&sort=recent&page=1
 */
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 });

  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 where: Record<string, unknown> = { brandId };
  const status = searchParams.get("status");
  if (status && status !== "all") {
    if (status === "toxic") where.toxicityScore = { gte: 60 };
    else where.status = status;
  }
  const domain = searchParams.get("domain");
  if (domain) where.sourceDomain = domain;

  const sort = searchParams.get("sort");
  const orderBy = sort === "authority" ? { domainAuthority: "desc" as const } : sort === "toxicity" ? { toxicityScore: "desc" as const } : sort === "relevance" ? { relevanceScore: "desc" as const } : { lastSeenAt: "desc" as const };

  const page = Math.max(1, Number(searchParams.get("page") || 1));
  const take = 50;
  const [backlinks, total] = await Promise.all([
    prisma.backlink.findMany({ where, orderBy, skip: (page - 1) * take, take }),
    prisma.backlink.count({ where }),
  ]);

  return NextResponse.json({ backlinks, total, page, pages: Math.ceil(total / take) });
}
