/**
 * POST /api/backlinks/[id]/analyze — re-run AI quality analysis on one backlink.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { analyzeQuality } from "@/lib/services/backlink-monitor";

export const dynamic = "force-dynamic";

export async function POST(_req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const bl = await prisma.backlink.findUnique({ where: { id: params.id }, include: { brand: { include: { organization: { include: { memberships: true } } } } } });
  if (!bl) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!bl.brand.organization.memberships.some((m) => m.userId === user.id)) return NextResponse.json({ error: "Access denied" }, { status: 403 });

  await analyzeQuality([{ id: bl.id, sourceDomain: bl.sourceDomain, anchorText: bl.anchorText }], bl.brand.industry || "general");
  const updated = await prisma.backlink.findUnique({ where: { id: params.id } });
  return NextResponse.json({ backlink: updated });
}
