const STORAGE_KEY = "livist-dashboard-current-user"

export type CachedCurrentUser = {
  name: string | null
  email: string
  image: string | null
}

export function getStoredCurrentUser(): CachedCurrentUser | null {
  if (typeof window === "undefined") return null
  try {
    const raw = window.localStorage.getItem(STORAGE_KEY)
    if (!raw) return null
    const parsed = JSON.parse(raw)
    if (
      typeof parsed !== "object" ||
      parsed === null ||
      typeof parsed.email !== "string"
    ) {
      window.localStorage.removeItem(STORAGE_KEY)
      return null
    }
    return {
      name: typeof parsed.name === "string" ? parsed.name : null,
      email: parsed.email,
      image: typeof parsed.image === "string" ? parsed.image : null,
    }
  } catch (err) {
    window.localStorage.removeItem(STORAGE_KEY)
    return null
  }
}

export function setStoredCurrentUser(user: CachedCurrentUser) {
  if (typeof window === "undefined") return
  window.localStorage.setItem(STORAGE_KEY, JSON.stringify(user))
}

export function clearStoredCurrentUser() {
  if (typeof window === "undefined") return
  window.localStorage.removeItem(STORAGE_KEY)
}
