/**
 * GET /api/rank-tracking/suggestions?brandId=X[&limit=100]
 *
 * Returns AI-powered keyword suggestions categorized as branded,
 * non-branded, local variations, Spanish keywords, and striking
 * distance opportunities. Sources: GSC, Site Tag, and AI analysis.
 */

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

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 { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  const limit = Math.min(parseInt(searchParams.get("limit") ?? "100", 10), 500);
  const includeAi = searchParams.get("includeAi") !== "false"; // default true

  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  try {
    const suggestions = await generateKeywordSuggestions(brandId, limit, includeAi);

    // Summary counts for the UI header
    const total =
      suggestions.branded.length +
      suggestions.nonBranded.length +
      suggestions.localVariations.length +
      suggestions.spanishKeywords.length +
      suggestions.strikingDistance.length;

    return NextResponse.json({ ...suggestions, total });
  } catch (err) {
    console.error("[rank-tracking/suggestions]", err);
    return NextResponse.json({ error: "Failed to generate suggestions" }, { status: 500 });
  }
}
