/**
 * GET /api/tasks/pipeline?brandId=X — tasks grouped by pipelineStage.
 */
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 GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const tasks = await prisma.task.findMany({
    where: { brandId, pipelineStage: { not: null } },
    orderBy: { updatedAt: "desc" },
    select: { id: true, title: true, pipelineStage: true, contentType: true, targetKeyword: true, priority: true, dueDate: true, assignedTo: true, briefId: true, studioPageId: true, publishedUrl: true, status: true },
  });

  const pipeline: Record<string, typeof tasks> = {};
  for (const s of STAGES) pipeline[s] = [];
  for (const t of tasks) { const s = t.pipelineStage || "idea"; if (pipeline[s]) pipeline[s].push(t); else pipeline.idea.push(t); }

  return NextResponse.json({ pipeline, stages: STAGES });
}
