/**
 * POST /api/ai-visibility/delete-by-query
 * ----------------------------------------
 * Body: { brandId: string; queries: string[] }
 *
 * Idempotent cleanup for both AiVisibilityQuery (tracked queries) AND
 * AiVisibilityCheck (cached AI responses) matching any of the given query
 * strings for a brand. Used by the UI's result-card Remove button and
 * bulk delete action — which operate on query TEXT, not row IDs — so
 * orphaned checks (rows in AiVisibilityCheck with no matching query row)
 * get wiped too. Previously the UI silently no-op'd on the DB in that
 * case, so a "deleted" query reappeared on the next page load.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const body = await req.json().catch(() => null) as { brandId?: string; queries?: string[] } | null;
  if (!body?.brandId || !Array.isArray(body.queries) || body.queries.length === 0) {
    return NextResponse.json({ error: "brandId and queries[] required" }, { status: 400 });
  }

  // Authorise: the user must belong to the brand's organisation. Without
  // this check anyone could wipe another org's visibility data since
  // AiVisibilityQuery has no owner column of its own.
  const brand = await prisma.brand.findUnique({
    where: { id: body.brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const queries = body.queries.map((q) => q.trim()).filter(Boolean);
  if (queries.length === 0) return NextResponse.json({ ok: true, queriesDeleted: 0, checksDeleted: 0 });

  const [queriesResult, checksResult] = await Promise.all([
    prisma.aiVisibilityQuery.deleteMany({ where: { brandId: body.brandId, query: { in: queries } } }),
    prisma.aiVisibilityCheck.deleteMany({ where: { brandId: body.brandId, query: { in: queries } } }),
  ]);

  return NextResponse.json({
    ok: true,
    queriesDeleted: queriesResult.count,
    checksDeleted: checksResult.count,
  });
}
