/**
 * GET /api/keyword-research/suggestions?brandId=xxx
 * Returns ~10 branded + ~10 non-branded AI-suggested keywords for the brand.
 * Used on the Keyword Research page to show clickable seed keyword chips
 * before the user types their own search.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { callLlm } from "@/lib/ai-avatar/llm-client";
import { getBrandLocations } from "@/lib/brand-helpers";

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

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

  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { profile: true, 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 gbp = await prisma.gbpLocation.findFirst({
    where: { brandId, isActive: true },
    select: { city: true, state: true },
  }).catch(() => null);

  const allLocations = getBrandLocations(brand);
  const city = gbp?.city || allLocations[0]?.split(",")[0]?.trim() || "";
  const state = gbp?.state || allLocations[0]?.split(",")[1]?.trim() || "";
  const location = city + (state ? `, ${state}` : "");

  const services = brand.profile?.services || [];
  const industry = brand.profile?.industry || brand.industry || "general";

  const prompt = `For ${brand.name} (${industry} business${location ? ` in ${location}` : ""}):
Services: ${services.slice(0, 5).join(", ") || industry}

Generate keyword research seed terms in two groups:
1. branded (8-10): searches a potential customer would use to find THIS business by name or unique attribute
2. nonBranded (8-10): topic/service keywords the business should rank for${city ? `, anchored to ${city}` : ""}

Good seed keywords are 2-4 words, research-worthy topics (not full questions).
Examples branded: "${brand.name} reviews", "${brand.name} ${city}"
Examples nonBranded: "${industry} in ${city}", "best ${industry} ${state}", "${services[0] || industry} near ${city}"

Return JSON: {"branded":["kw1","kw2"],"nonBranded":["kw1","kw2"]}`;

  const result = await callLlm(
    [
      { role: "system", content: "Generate keyword research seed terms. Respond ONLY with JSON." },
      { role: "user", content: prompt },
    ],
    () => JSON.stringify({
      branded: [`${brand.name} reviews`, `${brand.name} ${city}`, `${brand.name} services`],
      nonBranded: [`${industry} in ${city}`, `best ${industry} ${state}`, `${industry} cost`],
    }),
    { maxTokens: 800 },
  );

  try {
    const raw = result.reply.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/i, "");
    const parsed = JSON.parse(raw);
    return NextResponse.json({
      branded: (parsed.branded || []).slice(0, 10) as string[],
      nonBranded: (parsed.nonBranded || []).slice(0, 10) as string[],
    });
  } catch {
    return NextResponse.json({
      branded: [`${brand.name} reviews`, `${brand.name} ${city}`].filter(Boolean),
      nonBranded: [`${industry} in ${city}`, `best ${industry} ${state}`].filter(Boolean),
    });
  }
}
