<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useBackendEvents } from '@/common/backendEvents'
import { currentUserId, logoutParent, logoutUser, suppressForceLogout } from '@/stores/auth'
import { eventBus } from '@/common/eventBus'

const userId = ref(currentUserId.value)
const router = useRouter()

watch(currentUserId, (id) => {
  userId.value = id
})

// Always call useBackendEvents in setup, passing the reactive userId
useBackendEvents(userId)

function handleForceLogout(event: { payload?: { reason?: string } }) {
  if (suppressForceLogout.value) {
    suppressForceLogout.value = false
    return
  }
  logoutParent()
  logoutUser()
  if (event?.payload?.reason === 'account_deleted') {
    router.push('/')
  } else {
    router.push({ name: 'Login' })
  }
}

onMounted(() => {
  eventBus.on('force_logout', handleForceLogout)
})

onUnmounted(() => {
  eventBus.off('force_logout', handleForceLogout)
})
</script>

<template>
  <div></div>
</template>
