/**
 * POST /api/keyword-research/send-to-brief
 * Creates a Content Brief pre-populated with keyword research data.
 */

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; keyword?: string; relatedKeywords?: string[];
    questions?: string[]; type?: "seo" | "llmo";
  } | null;
  if (!body?.brandId || !body?.keyword) {
    return NextResponse.json({ error: "brandId and keyword 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 brief = await prisma.contentBrief.create({
    data: {
      brandId: body.brandId,
      type: body.type || "seo",
      title: `${body.keyword} — Content Brief`,
      status: "draft",
      primaryKeyword: body.keyword,
      secondaryKeywords: body.relatedKeywords?.slice(0, 10) ?? [],
      relatedQuestions: body.questions?.slice(0, 10) ?? [],
      brandName: brand.name,
      industry: brand.industry,
      createdById: user.id,
    },
  });

  return NextResponse.json({ briefId: brief.id });
}
