"use server"

import { revalidatePath } from "next/cache"

import {
  openLogin,
  resetPassword,
  setArchived,
  type LoginResult,
} from "@/lib/services/people"
import { requireAtLeast } from "@/lib/services/session"

/**
 * The three writes this screen owns, as thin adapters.
 *
 * Every one of them establishes who is asking before it does anything. A server
 * action is a public endpoint: the screen only being reachable by an admin says
 * nothing about who can call the function behind it, and these three hand out
 * passwords and withdraw access.
 *
 * `admin` and not `manager` on all three, per §8. A manager who could open a
 * login for their own staff would be a manager who could open one for anybody,
 * because nothing here scopes a person to a department.
 */

export async function createLogin(
  personId: string,
  username: string,
): Promise<LoginResult> {
  await requireAtLeast("admin")
  const result = await openLogin(personId, username)
  if (result.ok) revalidatePath(`/admin/people/${personId}`)
  return result
}

export async function newPassword(personId: string): Promise<LoginResult> {
  await requireAtLeast("admin")
  // No revalidate: nothing on the page changed. They had a login before and
  // they have one now, and the only new fact is the password, which is in the
  // answer and deliberately nowhere else.
  return resetPassword(personId)
}

export async function archivePerson(
  personId: string,
  archived: boolean,
): Promise<{ ok: boolean }> {
  await requireAtLeast("admin")
  const result = await setArchived(personId, archived)
  if (result.ok) {
    revalidatePath(`/admin/people/${personId}`)
    // The list marks who has left, so it is stale too.
    revalidatePath("/admin/people")
  }
  return result
}
