"use client"

import { useUserStore } from "@/app/store/user"
import { usePermissionStore } from "@/components/label/store/auth"
import { getUserPermission } from "@/components/login/api"
import { useCallback, useEffect } from "react"

export default function EntryCheck() {
  const user_info = useUserStore.getState().user_info
  const { setUserPermissionInfo } = usePermissionStore()

  const asyncGetUserPermission = useCallback(async () => {
    const { message: permissionRes } = await getUserPermission()
    const { uid, name } = permissionRes
    setUserPermissionInfo({
      user_id: uid,
      user_name: name,
      detailInfo: permissionRes,
    })
  }, [setUserPermissionInfo])

  useEffect(() => {
    if (!user_info.account) {
      window.location.href = "/login"
    } else {
      try {
        asyncGetUserPermission()
        window.location.href = `${process.env.NEXT_PUBLIC_BASE_PATH}/management`
      } catch {
        window.location.href = "/login"
      }
    }
  }, [asyncGetUserPermission, user_info.account])
  return <></>
}
