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 { canManageMarketing, mapMarketingMilestone } from "@/lib/marketing/persistence";

type CreateMilestoneBody = {
  title?: string;
  description?: string;
  dueDate?: string;
};

function parseDate(value: string | undefined): Date | null {
  if (!value) {
    return null;
  }

  const parsed = new Date(value);
  if (Number.isNaN(parsed.getTime())) {
    return null;
  }

  return parsed;
}

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 (!canManageMarketing(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owners or marketing leaders can create milestones." }, { status: 403 });
  }

  const initiativeId = context.params.id;
  const initiative = await prisma.marketingInitiative.findFirst({
    where: {
      id: initiativeId,
      department: DepartmentKey.marketing,
    },
    select: { id: true },
  });

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

  const body = (await request.json()) as CreateMilestoneBody;
  const title = body.title?.trim() ?? "";
  const description = body.description?.trim() ?? "";
  const dueDate = parseDate(body.dueDate);

  if (!title || !dueDate) {
    return NextResponse.json({ error: "title and dueDate are required." }, { status: 400 });
  }

  const lastMilestone = await prisma.marketingMilestone.findFirst({
    where: { initiativeId },
    orderBy: { sortOrder: "desc" },
    select: { sortOrder: true },
  });

  const milestone = await prisma.marketingMilestone.create({
    data: {
      initiativeId,
      title,
      description,
      dueDate,
      sortOrder: (lastMilestone?.sortOrder ?? 0) + 1,
      createdById: session.user.id,
      createdByName: session.user.name ?? session.user.email,
    },
    include: {
      checkpoints: {
        orderBy: { createdAt: "asc" },
      },
    },
  });

  await prisma.marketingInitiativeEdit.create({
    data: {
      initiativeId,
      editedById: session.user.id,
      editedByName: session.user.name ?? session.user.email ?? "Usuario",
      summary: `Milestone creado: ${title}`,
    },
  });

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