import { AppShell } from "@/components/app-shell"
import { NewTaskForm } from "@/components/new-task-form"
import { translator } from "@/lib/i18n"
import {
  assignablePositions,
  ownRecurringDuties,
  peopleInScope,
} from "@/lib/services/duties"
import { requireUser } from "@/lib/services/session"
import { occurrencesFor } from "@/lib/task-form"
import { OwnDuties } from "./own-duties"

/**
 * Creating work: for the department, or for yourself.
 *
 * One screen and one form, because a staff member adding a recurring reminder
 * is doing what this page already does. What the tier changes is how far the
 * two lists reach, and that is decided in `lib/services/duties.ts`: an admin
 * reaches every position, a manager their department, a staff member the one
 * position they hold. Both lists are re-derived by `createDuty` on the way in,
 * because a list narrowed on the way out is a list somebody can widen by
 * posting an id that was never on it.
 *
 * `requireUser` and not `requireAtLeast("manager")`, per `routes.md`: "creating
 * is a permission-gated ACTION, enforced in the service". A staff member whose
 * scope is empty, somebody between positions, sees a form with nothing to pick
 * and a service that refuses whatever they post.
 *
 * Open point G, answered on 3 August: recurring self to-dos are saved and
 * visible to the manager, one-time ones are not needed. So the radio group a
 * staff member is served has the four occurrences that repeat, and the manager
 * sees the work on `/team` like any other, because a self to-do is an ordinary
 * duty on an ordinary position and nothing marks it apart.
 */
export default async function Page() {
  const user = await requireUser()
  const [positions, people, own] = await Promise.all([
    assignablePositions(user),
    peopleInScope(user),
    ownRecurringDuties(user),
  ])

  const t = translator(user.language)
  const staff = user.tier === "staff"

  return (
    <AppShell
      title={staff ? "selfDuties.title" : "nav.createAndAssign"}
      user={user}
    >
      <div className="flex max-w-3xl flex-col gap-6">
        <NewTaskForm
          positions={positions}
          people={people}
          occurrences={occurrencesFor(user.tier)}
        />
        {/*
          Below the form and not above it. Somebody arrives here to add one; the
          ones they already have are what they come back for.
        */}
        {own.length > 0 ? <OwnDuties duties={own} t={t} /> : null}
      </div>
    </AppShell>
  )
}
