"use server"

import { revalidatePath } from "next/cache"

import { isLocale, type Locale } from "@/lib/i18n"
import { setLanguage as write } from "@/lib/services/people"
import { requireUser } from "@/lib/services/session"

/**
 * Changing the language somebody reads in.
 *
 * A thin adapter, like every other action here: it establishes who is asking
 * and hands the work to the service. The lint rule refused an earlier version
 * that wrote directly, which is the rule doing its job.
 *
 * `revalidatePath("/", "layout")` because the language is read by the shell,
 * and every screen renders inside it. Refreshing one page would leave the
 * navigation in the language somebody has just left.
 */
export async function setLanguage(locale: Locale): Promise<void> {
  if (!isLocale(locale)) return
  const user = await requireUser()
  await write(user.personId, locale)
  revalidatePath("/", "layout")
}
