<script lang="ts" setup>
import { toast } from 'vue-sonner'
import { Toaster } from '@/components/ui/sonner'

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

const onLoginExpired = () => {
  toast.error('登录过期，请重新登录')
  router.replace('/user/authenticate')
}

watch(
  () => loginState.isLoggedIn,
  (isLoggedIn) => {
    if (!isLoggedIn) {
      toast.info('账号已退出，请重新登录')
      router.replace('/user/authenticate')
    }
  },
)

onBeforeMount(() => {
  if (route.meta.requiresAuth && loginState.isLoggedIn) {
    loginState
      .checkLogin()
      .then((user) => {
        if (!user) {
          onLoginExpired()
        }
      })
      .catch(() => {
        onLoginExpired()
      })
  }
})
</script>

<template>
  <SidebarProvider>
    <TooltipProvider>
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
      <Toaster
        rich-colors
        close-button
        position="top-right"
        class="pointer-events-auto"
      />
    </TooltipProvider>
  </SidebarProvider>
</template>
