/**
 * POST /api/tasks/[id]/create-page — create a StudioPage linked to 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 slug = (task.targetKeyword || task.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 80);
  const page = await prisma.studioPage.create({
    data: {
      brandId: task.brandId, title: task.title, slug,
      purpose: task.contentType === "landing_page" ? "lead_generation" : "service",
      sections: [], branding: {}, settings: {},
    },
  });

  const nextStage = task.pipelineStage === "brief_created" ? "writing" : task.pipelineStage === "idea" ? "writing" : task.pipelineStage;
  await prisma.task.update({ where: { id: params.id }, data: { studioPageId: page.id, pipelineStage: nextStage } });
  return NextResponse.json({ pageId: page.id });
}
