import { Currency, DEFAULT_CURRENCY } from '@/app/(root)/account/constants';

const CURRENCY_STORAGE_KEY = 'suno-selected-currency';

/**
 * Gets the user's preferred currency from localStorage
 * Returns DEFAULT_CURRENCY if no preference is stored or if the stored value is invalid
 */
export const getUserCurrencyPreference = (): Currency => {
  if (typeof localStorage === 'undefined') {
    return DEFAULT_CURRENCY;
  }

  try {
    const storedCurrency = localStorage.getItem(CURRENCY_STORAGE_KEY);

    if (!storedCurrency) {
      return DEFAULT_CURRENCY;
    }

    // Validate that the stored currency is a valid Currency enum value
    const upperCurrency = storedCurrency.toUpperCase();
    if (Object.values(Currency).includes(upperCurrency as Currency)) {
      return upperCurrency as Currency;
    }

    // Invalid stored currency, fall back to default
    return DEFAULT_CURRENCY;
  } catch (error) {
    // localStorage access failed, fall back to default
    console.warn(
      'Failed to read currency preference from localStorage:',
      error
    );
    return DEFAULT_CURRENCY;
  }
};

/**
 * Stores the user's preferred currency in localStorage
 * Fails silently if localStorage is not available
 */
export const setUserCurrencyPreference = (currency: Currency): void => {
  if (typeof localStorage === 'undefined') {
    return;
  }

  try {
    localStorage.setItem(CURRENCY_STORAGE_KEY, currency);
  } catch (error) {
    // localStorage write failed, fail silently
    console.warn('Failed to save currency preference to localStorage:', error);
  }
};

/**
 * Gets currency from URL search parameters
 * Returns the currency if valid, undefined otherwise
 */
export const getCurrencyFromUrlParams = (
  searchParams: URLSearchParams
): Currency | undefined => {
  const currencyParam = searchParams.get('currency');

  if (!currencyParam) {
    return undefined;
  }

  // Validate that the URL parameter is a valid Currency enum value
  const upperCurrency = currencyParam.toUpperCase();
  if (Object.values(Currency).includes(upperCurrency as Currency)) {
    return upperCurrency as Currency;
  }

  return undefined;
};
