import type { Price, TPriceExpanded } from '../store/models';
import type { PriceCurrency } from '../store/models/types';

/**
 * Get price currency options for a given price
 */
export function getPriceCurrencyOptions(price: Price | TPriceExpanded | null | undefined): PriceCurrency[] {
  if (!price) {
    return [];
  }
  if (Array.isArray(price.currency_options)) {
    return price.currency_options;
  }

  return [
    {
      currency_id: price.currency_id,
      unit_amount: price.unit_amount,
      custom_unit_amount: price.custom_unit_amount || null,
      tiers: null,
    },
  ];
}

/**
 * Get price unit amount by currency ID
 */
export function getPriceUintAmountByCurrency(price: Price | TPriceExpanded, currencyId: string) {
  const options = getPriceCurrencyOptions(price);
  const option = options.find((x) => x.currency_id === currencyId);
  if (option) {
    if (option.custom_unit_amount) {
      return option.custom_unit_amount.preset || option.custom_unit_amount.presets[0];
    }
    return option.unit_amount;
  }

  if (price.currency_id === currencyId) {
    if (price.custom_unit_amount) {
      return price.custom_unit_amount.preset || price.custom_unit_amount.presets[0];
    }
    return price.unit_amount;
  }

  throw new Error(`Currency option ${currencyId} not configured for price ${price.id}`);
}
