"use server"

import { revalidatePath } from "next/cache"

import { setJobDescription, type WriteResult } from "@/lib/services/duties"
import { positionDetail } from "@/lib/services/positions"
import { requireAtLeast } from "@/lib/services/session"

/**
 * The two things the overview's sheet needs, as thin adapters.
 *
 * Same shape as `app/positions/[id]/actions.ts`: establish who is asking, hand
 * the work to a service, and let the service ask again whether that person may
 * touch this position. The screen showing a control is not a permission.
 */

export type EditablePosition = {
  title: string
  department: string
  jobDescription: string | null
  /** Only what the panel shows beside the textarea, not the whole duty. */
  duties: {
    id: string
    description: string
    occurrence: string
    active: boolean
  }[]
}

/**
 * Read one position when its panel opens, rather than sending 193 of them with
 * the table.
 *
 * The overview deliberately carries whether a description exists and not the
 * description itself: the text is only wanted by whoever opened the panel, and
 * shipping every paragraph to draw a column of badges would grow the page with
 * every description the client writes — which is the thing the screen exists to
 * encourage.
 *
 * `positionDetail` rather than a query of its own, so the panel and the
 * position page cannot disagree about what is on a position. It runs
 * `visibleTo`, which is the real guard here.
 */
export async function loadPosition(
  positionId: string,
): Promise<EditablePosition | null> {
  const user = await requireAtLeast("admin")
  const detail = await positionDetail(user, positionId)
  if (!detail) return null

  return {
    title: detail.title,
    department: detail.department,
    jobDescription: detail.jobDescription,
    duties: detail.duties.map((duty) => ({
      id: duty.id,
      description: duty.description,
      occurrence: duty.occurrence,
      active: duty.active,
    })),
  }
}

/**
 * Both paths are revalidated, and that is the point of writing from here.
 *
 * The overview draws a badge saying whether this text exists and the position
 * page draws the text itself. A save that refreshed only the screen somebody
 * was looking at would leave the other one asserting the opposite, which is
 * exactly the drift the single-write-surface rule was written to prevent.
 */
export async function saveJobDescription(
  positionId: string,
  text: string,
): Promise<WriteResult> {
  const user = await requireAtLeast("admin")
  const result = await setJobDescription(user, positionId, text)
  if (result.ok) {
    revalidatePath("/admin/job-descriptions")
    revalidatePath(`/positions/${positionId}`)
  }
  return result
}
