const LEGACY_SESSION_KEY = 'tkmind-h5-session-id';

export function resolveSessionStorageKey(userId?: string | null): string {
  return userId ? `${LEGACY_SESSION_KEY}:${userId}` : LEGACY_SESSION_KEY;
}

export function readStoredSessionId(userId?: string | null): string | null {
  if (userId) {
    // Only use per-user scoped storage. Do not migrate the legacy global key,
    // which may belong to another account on the same browser profile.
    return localStorage.getItem(resolveSessionStorageKey(userId));
  }
  return localStorage.getItem(LEGACY_SESSION_KEY);
}

export function writeStoredSessionId(userId: string | null | undefined, sessionId: string) {
  localStorage.setItem(resolveSessionStorageKey(userId), sessionId);
}

export function clearStoredSessionId(userId?: string | null) {
  localStorage.removeItem(resolveSessionStorageKey(userId));
  if (!userId) {
    localStorage.removeItem(LEGACY_SESSION_KEY);
  }
}

export function clearAllStoredSessionIds() {
  const keysToRemove: string[] = [];
  for (let i = 0; i < localStorage.length; i += 1) {
    const key = localStorage.key(i);
    if (!key) continue;
    if (key === LEGACY_SESSION_KEY || key.startsWith(`${LEGACY_SESSION_KEY}:`)) {
      keysToRemove.push(key);
    }
  }
  for (const key of keysToRemove) {
    localStorage.removeItem(key);
  }
}
