/**
 * POST /api/keyword-research/save — save keywords for future reference
 * GET  /api/keyword-research/saved?brandId=X — list saved keywords
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function authBrand(brandId: string, userId: string) {
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand) return { error: "Brand not found" as const, status: 404 };
  if (!brand.organization.memberships.some((m) => m.userId === userId)) return { error: "Access denied" as const, status: 403 };
  return { brand };
}

interface SaveInput { keyword: string; searchVolume?: number; difficulty?: number; cpc?: number; competition?: string; intent?: string; source?: string; tags?: string[]; group?: string; priority?: string }

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; keywords?: SaveInput[] } | null;
  if (!body?.brandId || !Array.isArray(body.keywords) || body.keywords.length === 0) {
    return NextResponse.json({ error: "brandId and keywords[] required" }, { status: 400 });
  }

  const resolved = await authBrand(body.brandId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  let saved = 0;
  for (const kw of body.keywords.slice(0, 200)) {
    if (!kw.keyword?.trim()) continue;
    await prisma.savedKeyword.upsert({
      where: { brandId_keyword: { brandId: body.brandId, keyword: kw.keyword.trim().toLowerCase() } },
      create: {
        brandId: body.brandId,
        keyword: kw.keyword.trim().toLowerCase(),
        searchVolume: kw.searchVolume ?? null,
        difficulty: kw.difficulty ?? null,
        cpc: kw.cpc ?? null,
        competition: kw.competition ?? null,
        intent: kw.intent ?? null,
        source: kw.source ?? "ai_estimated",
        tags: kw.tags ?? [],
        group: kw.group ?? null,
        priority: kw.priority ?? null,
      },
      update: {
        searchVolume: kw.searchVolume ?? undefined,
        difficulty: kw.difficulty ?? undefined,
        cpc: kw.cpc ?? undefined,
        competition: kw.competition ?? undefined,
        intent: kw.intent ?? undefined,
        tags: kw.tags ?? undefined,
        group: kw.group ?? undefined,
        priority: kw.priority ?? undefined,
      },
    });
    saved++;
  }

  return NextResponse.json({ saved });
}

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");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const resolved = await authBrand(brandId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const tag = searchParams.get("tag");
  const intent = searchParams.get("intent");
  const minDiff = Number(searchParams.get("minDifficulty") || 0);
  const maxDiff = Number(searchParams.get("maxDifficulty") || 100);

  const where: Record<string, unknown> = { brandId };
  if (tag) where.tags = { has: tag };
  if (intent) where.intent = intent;
  if (minDiff > 0 || maxDiff < 100) where.difficulty = { gte: minDiff, lte: maxDiff };

  const keywords = await prisma.savedKeyword.findMany({
    where,
    orderBy: { savedAt: "desc" },
  });

  return NextResponse.json({ keywords });
}
