/**
 * POST /api/keyword-research/for-brief
 * Quick keyword lookup shaped for the Keyword Strategy section on the
 * content brief pages. Returns primary kw with volume/difficulty, plus
 * secondary, long-tail, and question keywords.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { searchAndAnalyze, classifyIntent } 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; keyword?: string; city?: string; service?: string;
  } | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId 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 parts = [body.service, body.city].filter(Boolean);
  const seed = body.keyword?.trim() || parts.join(" ") || brand.industry || brand.name;
  if (!seed) return NextResponse.json({ error: "No keyword to research" }, { status: 400 });

  const result = await searchAndAnalyze(body.brandId, seed, "United States", "en");
  const primary = result.keywords.find((k) => k.keyword.toLowerCase() === seed.toLowerCase()) || result.keywords[0] || null;
  const secondary = result.keywords.filter((k) => k.keyword.toLowerCase() !== seed.toLowerCase()).slice(0, 6);
  const longTail = result.keywords.filter((k) => k.keyword.split(/\s+/).length >= 4).slice(0, 6).map((k) => k.keyword);
  const questions = result.keywords.filter((k) => /^(what|how|why|when|where|which|can|does|is)\s/i.test(k.keyword)).slice(0, 8).map((k) => k.keyword);

  return NextResponse.json({
    primary: primary ? { keyword: primary.keyword, searchVolume: primary.searchVolume, difficulty: primary.difficulty, cpc: primary.cpc, competition: primary.competition, intent: primary.intent || classifyIntent(primary.keyword) } : null,
    secondary: secondary.map((k) => ({ keyword: k.keyword, searchVolume: k.searchVolume, difficulty: k.difficulty, intent: k.intent })),
    longTail,
    questions,
    source: result.source,
  });
}
