import type { LedgerEntry } from "@cents/domain";

export function isReimbursement(entry: LedgerEntry) {
  return entry.type === "income" && Boolean(entry.reimbursementOfEntryId);
}

export function reimbursementsForExpense(entries: LedgerEntry[], expenseId: string) {
  return entries.filter((entry) =>
    entry.deletedAt === null
    && entry.reimbursementOfEntryId === expenseId,
  );
}

export function reimbursedOriginalAmount(expense: LedgerEntry, entries: LedgerEntry[]) {
  const amount = reimbursementsForExpense(entries, expense.id)
    .filter((entry) => entry.currency === expense.currency)
    .reduce((sum, entry) => sum + entry.amount, 0);
  return Math.min(expense.amount, amount);
}

export function reimbursedBaseAmount(expense: LedgerEntry, entries: LedgerEntry[]) {
  if (expense.baseAmount === null) return null;
  const reimbursed = reimbursedOriginalAmount(expense, entries);
  return Math.min(expense.baseAmount, Math.round(expense.baseAmount * reimbursed / expense.amount));
}

export function netOriginalAmount(expense: LedgerEntry, entries: LedgerEntry[]) {
  return Math.max(0, expense.amount - reimbursedOriginalAmount(expense, entries));
}

export function netBaseAmount(expense: LedgerEntry, entries: LedgerEntry[]) {
  if (expense.baseAmount === null) return null;
  return Math.max(0, expense.baseAmount - (reimbursedBaseAmount(expense, entries) ?? 0));
}
