/**
 * POST /api/keyword-research/analyze
 * Main entry point: raw data (DataForSEO or AI) + Claude strategic
 * analysis in brand context. Returns topic clusters, quick wins, gap
 * analysis, content plan, etc.
 */

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

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

/** GET /api/keyword-research/analyze?brandId=xxx — returns last 10 research sessions for this brand */
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 history = await prisma.keywordResearch.findMany({
    where: { brandId },
    orderBy: { createdAt: "desc" },
    take: 10,
    select: {
      id: true,
      seedKeyword: true,
      location: true,
      createdAt: true,
      results: true,
    },
  });
  return NextResponse.json({
    history: history.map((h) => ({
      id: h.id,
      seed: h.seedKeyword,
      location: h.location,
      date: h.createdAt.toISOString(),
      count: ((h.results as { keywords?: unknown[] })?.keywords?.length) ?? 0,
    })),
  });
}

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 });
  }

  try {
    const result = await searchAndAnalyze(body.brandId, body.seedKeyword.trim(), body.location || "United States", body.language || "en");
    logMemory({ brandId: body.brandId, category: "keyword_research", action: "generated", summary: `Keyword research for "${body.seedKeyword.trim()}" — ${result.keywords.length} keywords`, aiContext: `Researched "${body.seedKeyword.trim()}", found ${result.keywords.length} keywords, ${result.aiAnalysis.topicClusters?.length ?? 0} clusters` });
    return NextResponse.json(result);
  } catch (err) {
    console.error("[keyword-research/analyze]", err);
    return NextResponse.json({ error: "Analysis failed — try again" }, { status: 500 });
  }
}
