/**
 * POST /api/keyword-research/send-to-tracker
 * Creates TrackedKeyword records from saved keywords.
 */

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

export const dynamic = "force-dynamic";

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; keywordIds?: string[] } | null;
  if (!body?.brandId || !Array.isArray(body.keywordIds) || body.keywordIds.length === 0) {
    return NextResponse.json({ error: "brandId and keywordIds[] 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 saved = await prisma.savedKeyword.findMany({
    where: { id: { in: body.keywordIds }, brandId: body.brandId },
  });

  let created = 0;
  for (const kw of saved) {
    try {
      await prisma.trackedKeyword.create({
        data: { brandId: body.brandId, keyword: kw.keyword, tags: kw.tags },
      });
      created++;
    } catch {
      // Duplicate — skip
    }
  }

  return NextResponse.json({ sent: saved.length, created });
}
