import { AppShell } from "@/components/app-shell"
import { translator } from "@/lib/i18n"
import { requireAtLeast } from "@/lib/services/session"
import { PositionsTable } from "./positions-table"
import {
  countPositions,
  countVacantPositions,
  listDepartmentNames,
  listPositions,
} from "@/lib/services/positions"

/**
 * The list that leads to a position.
 *
 * Search and the department filter come from the url and are applied by the
 * query, so a narrowed view is a link somebody can send and a wider roster does
 * not become a bigger fetch. Nothing here knows the tables exist.
 */
export default async function Page({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>
}) {
  /**
   * Admin, and it is the more restrictive of two answers the client's own
   * documents give.
   *
   * functional-spec.md §3: "admin-only tabs: departments & positions tables",
   * and again in §8: "Structure tables (departments, positions, holders) are
   * Admin-only". machine/routes.json puts /positions in the manager guard group
   * and says "Manager tier: own department. Admin: all departments."
   *
   * They cannot both hold. Until the client says which, this takes the narrower
   * reading, because widening later shows somebody a list they were not seeing
   * and narrowing later takes away one they were. The service is already scoped
   * per viewer, so the day the answer arrives this line is the only change.
   * ELEVA-139.
   */
  const user = await requireAtLeast("admin")

  const params = await searchParams
  const query = (typeof params.q === "string" ? params.q : "").trim()
  const departments = Array.isArray(params.dept)
    ? params.dept
    : params.dept
      ? [params.dept]
      : []
  const vacantOnly = params.vacant === "1"

  const [rows, departmentNames, total, vacantCount] = await Promise.all([
    listPositions(user, { query, departments, vacantOnly }),
    listDepartmentNames(user),
    countPositions(user),
    countVacantPositions(user),
  ])

  const narrowed = Boolean(query || departments.length || vacantOnly)
  const t = translator(user.language)

  return (
    <AppShell title={"positions.title"} user={user}>
      <div className="flex flex-col gap-4">
        {/*
          Both counts go through the dictionary with the numbers in
          placeholders. Thai puts "แสดง" before the first figure and "จาก"
          between the two, so the sentence cannot be assembled from pieces the
          way this line used to assemble it.
        */}
        <p className="text-foreground/80">
          {narrowed
            ? t("positions.narrowed", { shown: rows.length, total })
            : t("positions.count", { total, vacant: vacantCount })}
        </p>
        <PositionsTable
          rows={rows}
          departments={departmentNames}
          vacantCount={vacantCount}
        />
      </div>
    </AppShell>
  )
}
