/**
 * POST /api/keyword-research/search
 * Quick keyword search — returns raw data without full AI analysis.
 * For the full strategic analysis, use /analyze instead.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { searchAndAnalyze } from "@/lib/services/keyword-research";

export const dynamic = "force-dynamic";
export const maxDuration = 60;

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; seedKeyword?: string; location?: string; language?: string } | null;
  if (!body?.brandId || !body?.seedKeyword?.trim()) {
    return NextResponse.json({ error: "brandId and seedKeyword required" }, { status: 400 });
  }

  const brand = await prisma.brand.findUnique({
    where: { id: body.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 result = await searchAndAnalyze(body.brandId, body.seedKeyword.trim(), body.location || "United States", body.language || "en");
  const questions = result.keywords.filter((k) => /^(what|how|why|when|where|which|can|does|is)\s/i.test(k.keyword)).map((k) => k.keyword);
  const longTail = result.keywords.filter((k) => k.keyword.split(/\s+/).length >= 4).slice(0, 10).map((k) => k.keyword);
  return NextResponse.json({ keywords: result.keywords, questions, longTail, source: result.source, cached: result.cached });
}
