<script setup lang="ts">
import { AccountApiClient, AccountHistoryItemType, type AccountHistoryItem, type AccountHistoryJournalEntryItem, type AccountHistoryValueRecordItem } from '@/api/account';
import type { PageRequest } from '@/api/pagination';
import { onMounted, ref, type Ref } from 'vue';
import ValueRecordHistoryItem from './ValueRecordHistoryItem.vue';
import JournalEntryHistoryItem from './JournalEntryHistoryItem.vue';
import { useRoute } from 'vue-router';

const route = useRoute()
const props = defineProps<{ accountId: number }>()
const historyItems: Ref<AccountHistoryItem[]> = ref([])

onMounted(async () => {
  const pageRequest: PageRequest = { page: 1, size: 10, sorts: [{ attribute: 'timestamp', dir: 'DESC' }] }
  const api = new AccountApiClient(route)
  while (true) {
    try {
      const page = await api.getHistory(props.accountId, pageRequest)
      historyItems.value.push(...page.items)
      if (page.isLast) return
      pageRequest.page++
    } catch (err) {
      console.error(err)
      historyItems.value = []
      return
    }
  }
})

function asVR(i: AccountHistoryItem): AccountHistoryValueRecordItem {
  return i as AccountHistoryValueRecordItem
}

function asJE(i: AccountHistoryItem): AccountHistoryJournalEntryItem {
  return i as AccountHistoryJournalEntryItem
}
</script>
<template>
  <div>
    <div v-for="item in historyItems" :key="item.timestamp" class="history-item">
      <div class="history-item-header">
        <div class="history-item-header-timestamp">{{ new Date(item.timestamp).toLocaleString() }}</div>
        <div>{{ item.type }}</div>
      </div>

      <ValueRecordHistoryItem v-if="item.type === AccountHistoryItemType.VALUE_RECORD" :item="asVR(item)"
        :account-id="accountId" />

      <JournalEntryHistoryItem v-if="item.type === AccountHistoryItemType.JOURNAL_ENTRY" :item="asJE(item)" />
    </div>
  </div>
</template>
<style lang="css">
.history-item {
  margin-top: 1rem;
  margin-bottom: 1rem;
  padding: 0.25rem 1rem;
  background-color: var(--bg-secondary);
  border-radius: 1rem;
}

.history-item-header {
  float: right;
  text-align: right;
}

.history-item-header-timestamp {
  font-family: monospace;
  font-size: 12px;
}

.history-item-content {
  padding: 0.5rem 0;
}
</style>
