<script setup lang="ts">

import {findAllTransactionInLeger, TransferTypes, useLedgerParam} from "@/ledger";
import {computedAsync} from "@vueuse/core";
import {TransactionResponse} from "@/generated/mammon";
import {formatEveDate} from "@/formaters.ts";
import {IskLabel} from "@/market";

const {ledgerId} = useLedgerParam();

const transactions = computedAsync<TransactionResponse[]>(async () => {
  if (ledgerId.value) {
    return await findAllTransactionInLeger(ledgerId.value);
  }
  return [];
}, []);

const getIskBalance = (transaction: TransactionResponse) => {
  if (!ledgerId.value) {
    return 0;
  }

  let balance = 0;

  for (const transfer of transaction.transfers) {
    if (transfer.type === TransferTypes.Isk) {
      if (transfer.toLedgerId === ledgerId.value) {
        balance += transfer.amount;
      } else if (transfer.fromLedgerId === ledgerId.value) {
        balance -= transfer.amount;
      }
    }
  }
  return balance;
}
</script>

<template>
  <div class="mt-4">
    <div class="flex items-end gap-2 mt-2" v-for="transaction in transactions" :key="transaction.transactionId">
      <span>{{formatEveDate(new Date(transaction.datetime))}}</span>
      <IskLabel :amount="getIskBalance(transaction)" />
      <span>{{transaction.description}}</span>
    </div>
  </div>
</template>
