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, mapProjectTask } from "@/lib/projects/persistence";

type CreateTaskBody = {
  initiativeId?: string;
  title?: string;
  description?: string;
  assigneeId?: 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) {
  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 create tasks." }, { status: 403 });
  }

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

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

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

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

  const task = await prisma.marketingTask.create({
    data: {
      initiativeId,
      title,
      description,
      assigneeId: assigneeId || null,
      dueDate,
      status: "todo",
    },
    include: {
      evidenceLinks: true,
    },
  });

  return NextResponse.json({
    ok: true,
    task: mapProjectTask(task),
  });
}
