import { safeJsonParse } from '@/lib/utils';

export function getUserId(): string {
  if (typeof window === 'undefined') return 'default';
  const userStr = localStorage.getItem('user');
  if (!userStr) return 'default';
  const user = safeJsonParse<Record<string, unknown> | null>(userStr, null);
  return user?.id ? String(user.id) : 'default';
}

export function getStorageKey(baseKey: string): string {
  return `${baseKey}-${getUserId()}`;
}

export function createUserStorage(baseKey: string) {
  return {
    getItem: (_name: string) => {
      const key = getStorageKey(baseKey);
      const str = localStorage.getItem(key);
      if (!str) return null;
      return JSON.parse(str);
    },
    setItem: (name: string, value: unknown) => {
      const key = getStorageKey(baseKey);
      localStorage.setItem(key, JSON.stringify(value));
    },
    removeItem: (_name: string) => {
      const key = getStorageKey(baseKey);
      localStorage.removeItem(key);
    },
  };
}
