/**
 * POST /api/tasks/[id]/generate-brief — create a ContentBrief from the task.
 */
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, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const task = await prisma.task.findUnique({
    where: { id: params.id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!task) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!task.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: task.brandId,
      type: task.contentType?.includes("landing") ? "seo" : "seo",
      title: `${task.targetKeyword || task.title} — Content Brief`,
      status: "draft",
      primaryKeyword: task.targetKeyword,
      brandName: task.brand.name,
      industry: task.brand.industry,
      createdById: user.id,
    },
  });

  await prisma.task.update({ where: { id: params.id }, data: { briefId: brief.id, pipelineStage: task.pipelineStage === "idea" ? "brief_created" : task.pipelineStage } });
  return NextResponse.json({ briefId: brief.id });
}
