<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import bus, { SYNC } from '@/utils/bus-event'
import type IAccount from '@/models/IAccount'
import type ITransaction from '@/models/ITransaction'
import accountService from '@/services/AccountService'
import transactionService from '@/services/TransactionService'
import queueNotifService from '@/services/QueueNotifService'
import TransactionCreate from '@/components/TransactionCreate.vue'

const props = defineProps<{ id: string }>()
const router = useRouter()

const account = ref<IAccount | null>(null)
const transaction = ref<ITransaction | null>(null)

const getData = async (docIds?: string[]) => {
  if (docIds && !docIds.find((i) => i === props.id)) return
  transaction.value = await transactionService.get(props.id)
  if (!transaction.value) {
    router.push({ name: 'home' })
    queueNotifService.error('Compte inexistant.')
    return
  }
  account.value = await accountService.get(transaction.value.accountId)
}

onMounted(() => {
  getData()
  bus.on(SYNC, getData)
})

onBeforeUnmount(() => {
  bus.off(SYNC, getData)
})
</script>

<template>
  <div v-if="account && transaction" class="transaction-update p-4">
    <TransactionCreate :account="account" :transaction="transaction" />
  </div>
</template>
