"use server"

import { revalidatePath } from "next/cache"

import {
  createDuty,
  setOwnDutyActive,
  type CreateResult,
  type NewDuty,
  type WriteResult,
} from "@/lib/services/duties"
import { requireUser } from "@/lib/services/session"

/**
 * Creating a duty.
 *
 * The signed-in person is read here and never taken from the form. Who is
 * allowed to assign to whom is the one thing a browser must not be trusted
 * about, and a `createdBy` that arrives in a request body is a `createdBy`
 * somebody can put a colleague's name in.
 *
 * `requireUser` and not `requireAtLeast("manager")`, since 3 August. Creating
 * is a permission-gated action rather than a tier's area, which is what
 * `routes.md` says of this url: "nav shows it to the manager tier, the service
 * enforces it for everyone." What the tier now changes is how far the two lists
 * reach, and `withinScope` is where that is decided. A staff member reaches one
 * position, their own.
 */
export async function submitDuty(duty: NewDuty): Promise<CreateResult> {
  const user = await requireUser()
  return createDuty(user, duty)
}

/**
 * Stopping a duty somebody wrote for themselves, or starting it again.
 *
 * `requireUser`, so the whole of the answer is `setOwnDutyActive`: the duty has
 * to sit on the caller's own position and have been written by them. This page
 * is not a write surface for anybody else's duties, and the narrower service is
 * what keeps that true of a posted id as well as of a pressed button.
 *
 * Nothing is deleted, because the instances the duty already produced are
 * somebody's history.
 */
export async function toggleOwnDuty(
  dutyId: string,
  active: boolean,
): Promise<WriteResult> {
  const user = await requireUser()
  const result = await setOwnDutyActive(user, dutyId, active)
  // This page lists them, so this page is what changed. The task list is not
  // revalidated with it: switching a duty off leaves every instance it has
  // already produced exactly where it was.
  if (result.ok) revalidatePath("/tasks/new")
  return result
}
