import { getLogout, postLogin } from '@api/auth'
import { AuthContext } from '@context/auth-context'
import { PathConstants } from '@routes/routes'
import { LOGIN_KEY } from '@utils/enum'
import { Helpers } from '@utils/helper'
import { useContext } from 'react'
import { useNavigate } from 'react-router-dom'

export function useSignInUp(setAuth) {
  const navigate = useNavigate()

  const onLogin = async ({ username, password }) => {
    const resp = await postLogin({ username, password })

    if (resp.status === 200) {
      const token = resp.data || {}
      if (token) {
        const { name, ...rest } = token
        setAuth({ isLogged: true, userInfo: { name } })
        localStorage.setItem(LOGIN_KEY, Helpers.encrypt(JSON.stringify(rest)))
      }
      navigate('/')
    }
  }

  const onLogout = async () => {
    await getLogout()
    Helpers.clearStorage()
    setAuth({ isLogged: false, userInfo: null })
    navigate(PathConstants.LOGIN)
  }
  return { onLogin, onLogout }
}

export function useAuth() {
  return useContext(AuthContext)
}
