import type { UserProfile, UserPreferences } from "@/types";

const STORAGE_KEY = "nowhatever_user_id";
const PROFILE_KEY = "nowhatever_profile";

export function getUserId(): string {
  if (typeof window === "undefined") return "";

  let id = localStorage.getItem(STORAGE_KEY);
  if (!id) {
    id = crypto.randomUUID();
    localStorage.setItem(STORAGE_KEY, id);
  }
  return id;
}

export function getCachedProfile(): UserProfile | null {
  if (typeof window === "undefined") return null;
  try {
    const raw = localStorage.getItem(PROFILE_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
}

export function setCachedProfile(profile: UserProfile | null): void {
  if (typeof window === "undefined") return;
  if (profile) {
    localStorage.setItem(PROFILE_KEY, JSON.stringify(profile));
  } else {
    localStorage.removeItem(PROFILE_KEY);
  }
  window.dispatchEvent(new CustomEvent("nowhatever_auth"));
}

export function isRegistered(): boolean {
  return getCachedProfile() !== null;
}

export function getCachedPreferences(): UserPreferences {
  if (typeof window === "undefined") return {};
  try {
    const profile = getCachedProfile();
    if (!profile) return {};
    const raw = localStorage.getItem("nowhatever_preferences");
    return raw ? JSON.parse(raw) : {};
  } catch {
    return {};
  }
}

export function setCachedPreferences(prefs: UserPreferences): void {
  if (typeof window === "undefined") return;
  localStorage.setItem("nowhatever_preferences", JSON.stringify(prefs));
}

export function logout(): void {
  if (typeof window === "undefined") return;
  localStorage.removeItem(PROFILE_KEY);
  localStorage.removeItem("nowhatever_preferences");
  const newId = crypto.randomUUID();
  localStorage.setItem(STORAGE_KEY, newId);
  window.dispatchEvent(new CustomEvent("nowhatever_auth"));
}
