const CURRENCY_PREFERENCE_KEY_BASE = 'payment-currency-preference';

export const getUserStorageKey = (base: string, did?: string) => {
  return did ? `${base}:${did}` : base;
};

export const saveCurrencyPreference = (currencyId: string, did?: string) => {
  try {
    localStorage.setItem(getUserStorageKey(CURRENCY_PREFERENCE_KEY_BASE, did), currencyId);
  } catch (e) {
    console.warn('Failed to save currency preference', e);
  }
};

export const getCurrencyPreference = (did?: string, availableCurrencyIds?: string[]) => {
  try {
    const saved = localStorage.getItem(getUserStorageKey(CURRENCY_PREFERENCE_KEY_BASE, did));
    if (saved && (!availableCurrencyIds || availableCurrencyIds.includes(saved))) {
      return saved;
    }
  } catch (e) {
    console.warn('Failed to access localStorage', e);
  }
  return null;
};
