function activeAccounts(accounts) {
  return accounts.filter((account) => account.status === "active");
}

function selectAccount(accounts, order, strategy = "balance-aware") {
  const candidates = activeAccounts(accounts);
  if (candidates.length === 0) {
    throw new Error("No active Smile.one accounts are available");
  }

  if (strategy === "round-robin") {
    return candidates
      .slice()
      .sort((left, right) => {
        const leftUsed = left.last_used || "";
        const rightUsed = right.last_used || "";
        return leftUsed.localeCompare(rightUsed);
      })[0];
  }

  return candidates
    .filter((account) => Number(account.balance || 0) >= Number(order.amount || 0))
    .sort((left, right) => Number(right.balance || 0) - Number(left.balance || 0))[0] || candidates[0];
}

module.exports = {
  selectAccount,
};
