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);
  if (!body?.brandId || !body?.queries?.length) return NextResponse.json({ error: "brandId and queries[] required" }, { status: 400 });
  type QueryInput = string | { query: string; intent?: string; targetLocation?: string };
  const saved = [];
  for (const item of body.queries as QueryInput[]) {
    const q = typeof item === "string" ? item : item.query;
    const intent = typeof item === "object" ? item.intent : undefined;
    const targetLocation = typeof item === "object" ? item.targetLocation : undefined;
    try {
      const record = await prisma.aiVisibilityQuery.upsert({
        where: { brandId_query: { brandId: body.brandId, query: q } },
        update: { isActive: true },
        create: {
          brandId: body.brandId,
          query: q,
          category: body.category || "general",
          ...(intent ? { intent } : {}),
          ...(targetLocation ? { targetLocation } : {}),
        },
      });
      saved.push(record);
    } catch { /* skip duplicates */ }
  }
  return NextResponse.json({ saved: saved.length });
}
