/**
 * POST /api/keyword-research/related
 * Returns related keywords + question-format keywords for a seed.
 */

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 } | 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", "en");
  const questions = result.keywords.filter((k: { keyword: string }) => /^(what|how|why|when|where|which|can|does|is)\s/i.test(k.keyword)).map((k: { keyword: string }) => k.keyword);
  const longTail = result.keywords.filter((k: { keyword: string }) => k.keyword.split(/\s+/).length >= 4).slice(0, 10).map((k: { keyword: string }) => k.keyword);
  return NextResponse.json({
    related: result.keywords.filter((k: { keyword: string }) => k.keyword.toLowerCase() !== body.seedKeyword!.trim().toLowerCase()),
    questions,
    longTail,
  });
}
