import { STORAGE_KEY_CURRENT_USER_ID } from '../constants';

const METOYOU_STORAGE_PREFIX = 'metoyou_';

function normaliseStorageUserId(userId?: string | null): string | null {
  const trimmedUserId = userId?.trim();

  return trimmedUserId || null;
}

export function getStoredCurrentUserId(): string | null {
  try {
    const raw = normaliseStorageUserId(localStorage.getItem(STORAGE_KEY_CURRENT_USER_ID));

    return raw || null;
  } catch {
    return null;
  }
}

export function getUserScopedStorageKey(baseKey: string, userId?: string | null): string {
  const scopedUserId = userId === undefined
    ? getStoredCurrentUserId()
    : normaliseStorageUserId(userId);

  return scopedUserId
    ? `${baseKey}__${encodeURIComponent(scopedUserId)}`
    : baseKey;
}

export function setStoredCurrentUserId(userId: string): void {
  try {
    localStorage.setItem(STORAGE_KEY_CURRENT_USER_ID, userId);
  } catch {}
}

export function clearStoredCurrentUserId(): void {
  try {
    localStorage.removeItem(STORAGE_KEY_CURRENT_USER_ID);
  } catch {}
}

export function clearStoredLocalAppData(): void {
  try {
    const keysToRemove: string[] = [];

    for (let index = 0; index < localStorage.length; index += 1) {
      const key = localStorage.key(index);

      if (key?.startsWith(METOYOU_STORAGE_PREFIX)) {
        keysToRemove.push(key);
      }
    }

    for (const key of keysToRemove) {
      localStorage.removeItem(key);
    }
  } catch {}
}
