import { prisma } from "@/lib/prisma";
import { requirePermission, withGuard, HttpError } from "@/lib/guard";
import { parseBody, ok } from "@/lib/http";
import { createTaskSchema } from "@/lib/validators";
import { getIsoWeek } from "@/lib/week";
import { z } from "zod";
import type { Prisma } from "@prisma/client";

export const runtime = "nodejs";

const INCLUDE = {
  user: { select: { id: true, name: true, position: true } },
  contributions: { include: { kpiIndicator: true } },
} satisfies Prisma.TaskInclude;

// Admin intervention requires an explicit target staff member.
const overrideSchema = createTaskSchema.extend({
  userId: z.string().uuid(),
});

// POST /api/tasks/override — Manager-tier directly injects a task into a
// specific staff member's queue. Session + permission validated server-side
// BEFORE execution (non-functional security requirement).
export const POST = withGuard(async (req: Request) => {
  const me = await requirePermission("tasks:manageAll");
  const data = await parseBody(req, overrideSchema);

  const target = await prisma.user.findUnique({ where: { id: data.userId } });
  if (!target || !target.active) throw new HttpError(404, "Target staff not found");

  const due = data.dueDate ? new Date(data.dueDate) : null;
  const { week, year } = getIsoWeek(due ?? new Date());

  const task = await prisma.task.create({
    data: {
      title: data.title,
      description: data.description ?? null,
      status: data.status ?? "TO_DO",
      priority: data.priority ?? "MEDIUM",
      channel: data.channel ?? null,
      dueDate: due,
      weekNumber: week,
      weekYear: year,
      userId: target.id,
      createdById: me.id, // tracks who intervened
    },
    include: INCLUDE,
  });
  return ok(task, 201);
});
