import { storeToRefs } from 'pinia'

import { useAdminLoginMutation } from '@/services/api/monisuo-admin.api'
import { useAuthStore } from '@/stores/auth'

export function useAuth() {
  const router = useRouter()

  const authStore = useAuthStore()
  const { isLogin, adminInfo } = storeToRefs(authStore)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const loginMutation = useAdminLoginMutation()

  function logout() {
    authStore.logout()
    router.push({ path: '/auth/sign-in' })
  }

  function toHome() {
    router.push({ path: '/monisuo/dashboard' })
  }

  async function login(username: string, password: string) {
    loading.value = true
    error.value = null

    try {
      const result = await loginMutation.mutateAsync({ username, password })

      if (result.code === '0000' && result.data) {
        authStore.setToken(result.data.token)
        authStore.setAdminInfo(result.data.adminInfo)

        const redirect = router.currentRoute.value.query.redirect as string
        if (!redirect || redirect.startsWith('//')) {
          toHome()
        }
        else {
          router.push(redirect)
        }
      }
      else {
        error.value = result.msg || '登录失败'
      }
    }
    catch (e: any) {
      error.value = e.response?.data?.msg || '网络错误，请稍后重试'
    }
    finally {
      loading.value = false
    }
  }

  return {
    loading,
    error,
    isLogin,
    adminInfo,
    logout,
    login,
  }
}
