export async function calculate(members, expenses) {
  if (!members.length || !expenses.length) return [];

  const totalAmount = expenses.map(e => e.amount).reduce((accumulator, amount) => accumulator + amount);
  const targetAmountPerUser = Math.floor(totalAmount / members.length);

  const debts = {};
  const transfers = [];

  for (const member of members) {
    const expensesOfMember = expenses.filter(e => e.creator.id === member.id);

    if (!expensesOfMember.length) {
      debts[member.name] = targetAmountPerUser;
    } else {
      const expenseSumOfMember = expensesOfMember.map(e => e.amount).reduce((accumulator, value) => accumulator + value, 0);
      debts[member.name] = targetAmountPerUser - expenseSumOfMember;
    }
  }

  for (const payer in debts) {
    for (const recipient in debts) {
      if (payer === recipient) continue;
      if (debts[payer] <= 0) break; // if payer has no debts (anymore)
      if (debts[recipient] >= 0) continue; // if recipient has debts

      const transferAmount = Math.min(debts[payer], -debts[recipient]);

      debts[payer] -= transferAmount;
      debts[recipient] += transferAmount;

      transfers.push({from: payer, to: recipient, amount: transferAmount});
    }
  }

  return transfers;
}