import { BonusCardInfo } from '../models';

export function getPrimaryBonusCard(
  bonusCards: BonusCardInfo[],
): BonusCardInfo | undefined {
  if (bonusCards.length === 0) {
    return undefined;
  }

  // Filter primary cards if any exist
  const primaryCards = bonusCards.filter((card) => card.isPrimary);

  // Use primary cards if available, otherwise use all cards
  const cardsToSort = primaryCards.length > 0 ? primaryCards : bonusCards;

  // Sort alphabetically by code and return the first one
  return cardsToSort.sort((a, b) => {
    const codeA = a.code?.toLowerCase() ?? '';
    const codeB = b.code?.toLowerCase() ?? '';
    return codeA.localeCompare(codeB);
  })[0];
}
