const ACTIVE_KEY = "nexus-session-active";

export type StoredSession = {
  sessionId: string | null;
  messages: Array<{
    role: string;
    content: string | Array<{ type: string; [key: string]: unknown }>;
    name?: string;
    tool_call_id?: string;
    _images?: string[];
  }>;
};

const defaults: StoredSession = {
  sessionId: null,
  messages: [],
};

export function loadSession(): StoredSession {
  if (typeof window === "undefined") return defaults;
  try {
    const raw = localStorage.getItem(ACTIVE_KEY);
    return raw ? { ...defaults, ...JSON.parse(raw) } : defaults;
  } catch {
    return defaults;
  }
}

export function saveSession(session: StoredSession): void {
  try {
    localStorage.setItem(ACTIVE_KEY, JSON.stringify(session));
  } catch {
    // localStorage full or unavailable — silently fail
  }
}

export function clearSession(): void {
  localStorage.removeItem(ACTIVE_KEY);
}
