/**
 * PUT /api/tasks/[id]/stage — kanban drag between pipeline stages.
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const STAGES = ["idea", "brief_created", "writing", "editing", "review", "approved", "published"];

export async function PUT(req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const body = await req.json().catch(() => null) as { pipelineStage?: string } | null;
  if (!body?.pipelineStage || !STAGES.includes(body.pipelineStage)) return NextResponse.json({ error: "Valid pipelineStage required" }, { status: 400 });

  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 data: Record<string, unknown> = { pipelineStage: body.pipelineStage };
  if (body.pipelineStage === "published") { data.publishedAt = new Date(); data.status = "completed"; data.completedAt = new Date(); }

  await prisma.task.update({ where: { id: params.id }, data });
  return NextResponse.json({ ok: true });
}
