<script setup lang="ts">
import { defaultPage, type Page, type PageRequest } from '@/api/pagination'
import { getSelectedProfile } from '@/api/profile'
import {
  TransactionApiClient,
  type TransactionsListItem,
  type TransactionVendor,
} from '@/api/transaction'
import AppPage from '@/components/common/AppPage.vue'
import PaginationControls from '@/components/common/PaginationControls.vue'
import TransactionCard from '@/components/TransactionCard.vue'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const vendor = ref<TransactionVendor | undefined>()
const relatedTransactionsPage = ref<Page<TransactionsListItem>>(defaultPage())

onMounted(async () => {
  const vendorId = parseInt(route.params.id as string)
  try {
    const api = new TransactionApiClient(getSelectedProfile(route))
    vendor.value = await api.getVendor(vendorId)
    await fetchPage(1)
  } catch (err) {
    console.error(err)
    await router.replace('/')
  }
})

async function fetchPage(pg: number) {
  if (!vendor.value) return
  const pageRequest: PageRequest = {
    page: pg,
    size: 10,
    sorts: [
      {
        attribute: 'txn.timestamp',
        dir: 'DESC',
      },
    ],
  }
  const params = new URLSearchParams()
  params.append('vendor', vendor.value?.id + '')
  const api = new TransactionApiClient(getSelectedProfile(route))
  relatedTransactionsPage.value = await api.searchTransactions(params, pageRequest)
}
</script>
<template>
  <AppPage
    v-if="vendor"
    :title="'Vendor - ' + vendor.name"
  >
    <p>
      {{ vendor.description }}
    </p>

    <div>
      <h3 class="mb-0">Transactions</h3>
      <p class="text-muted font-size-small mt-0">
        Below is a list of all transactions recorded with this vendor.
      </p>
      <PaginationControls
        :page="relatedTransactionsPage"
        @update="(pr) => fetchPage(pr.page)"
        class="align-right"
      />
      <TransactionCard
        v-for="txn in relatedTransactionsPage.items"
        :key="txn.id"
        :tx="txn"
      />
    </div>
  </AppPage>
</template>
