import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canManageProjects, mapProjectMilestone } from "@/lib/projects/persistence";

type CreateCheckpointBody = {
  note?: string;
};

export async function POST(request: Request, context: { params: { id: string } }) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageProjects(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owners or projects leaders can add checkpoints." }, { status: 403 });
  }

  const milestoneId = context.params.id;
  const milestone = await prisma.marketingMilestone.findFirst({
    where: {
      id: milestoneId,
      initiative: { department: DepartmentKey.proyectos },
    },
    select: {
      id: true,
      initiativeId: true,
    },
  });

  if (!milestone) {
    return NextResponse.json({ error: "Milestone not found." }, { status: 404 });
  }

  const body = (await request.json()) as CreateCheckpointBody;
  const note = body.note?.trim() ?? "";

  if (note.length === 0) {
    return NextResponse.json({ error: "Checkpoint note is required." }, { status: 400 });
  }

  await prisma.marketingMilestoneCheckpoint.create({
    data: {
      milestoneId,
      note,
      createdById: session.user.id,
      createdByName: session.user.name ?? session.user.email,
    },
  });

  const refreshed = await prisma.marketingMilestone.findUniqueOrThrow({
    where: { id: milestoneId },
    include: {
      checkpoints: {
        orderBy: { createdAt: "asc" },
      },
    },
  });

  await prisma.marketingInitiativeEdit.create({
    data: {
      initiativeId: milestone.initiativeId,
      editedById: session.user.id,
      editedByName: session.user.name ?? session.user.email ?? "Usuario",
      summary: `Checkpoint agregado a milestone`,
    },
  });

  return NextResponse.json({
    ok: true,
    milestone: mapProjectMilestone(refreshed),
  });
}
