import { getLogout, postLogin } from '@api/auth'
import { useNavigate } from '@solidjs/router'
import { LOGIN_KEY } from '@utils/enum'
import { Helpers } from '@utils/helper'

export default function useAuth(setAuth) {
  const navigate = useNavigate()

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

    if (resp.status === 200) {
      const token = resp.data || {}
      if (token) {
        const { name, ...rest } = token
        setAuth({ auth: true, user: { name } })
        localStorage.setItem(LOGIN_KEY, Helpers.encrypt(JSON.stringify(rest)))
      }

      navigate('/', { replace: true })
    }
  }

  const clickLogOut = async () => {
    await getLogout()
    Helpers.clearStorage()
    setAuth({ auth: false, user: null })
    navigate('/login', { replace: true })
  }

  return {
    clickLogOut,
    clickLogIn,
  }
}
