// Client-side cache of the signed-in user's PROFILE, for display only.
//
// This is not an auth mechanism and holds no credentials: the session is the httpOnly
// `erp_at` cookie, which JS cannot read and which the API validates on every call. This
// exists only because there is no `GET /auth/me` endpoint — the user object arrives once,
// in the login/register response (docs/11 §2.0) — and the Header needs a name to show.
//
// Treat it as untrusted display data. Clearing it does not log anyone out; only the
// server clearing the cookie does that.
import { AuthUser } from "@/types/auth"

const KEY = "erpcore.user"

export function setStoredUser(user: AuthUser | null): void {
  if (typeof window === "undefined") return
  if (!user) {
    window.localStorage.removeItem(KEY)
    return
  }
  window.localStorage.setItem(KEY, JSON.stringify(user))
}

export function getStoredUser(): AuthUser | null {
  if (typeof window === "undefined") return null
  const raw = window.localStorage.getItem(KEY)
  if (!raw) return null
  try {
    return JSON.parse(raw) as AuthUser
  } catch {
    // Corrupt/legacy value — drop it rather than crash the shell.
    window.localStorage.removeItem(KEY)
    return null
  }
}

export function clearStoredUser(): void {
  setStoredUser(null)
}

/** Best display name available, falling back through the fields AuthHex may leave null. */
export function displayName(user: AuthUser | null): string {
  if (!user) return "Signed in"
  return user.fullname?.trim() || user.userName?.trim() || user.email?.trim() || "Signed in"
}
