import { useState } from "react"
import { API_URL } from "../../config"

function useAuth() {
    const [loading, setLoading] = useState(false)
    const [error, setError] = useState('')

    const doAuth = async (data, newAccount) => {
        setLoading(true)

        if (newAccount) {
            try {
                const res = await fetch(API_URL + "/signup", {
                    method: "POST",
                    body: data,
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                const signupData = await res.json()

                if (signupData.Success === false) {
                    throw new Error(signupData.Message)
                }
            } catch (err) {
                setError(err.message)
                setLoading(false)
                return null
            }
        }

        try {
            const res = fetch(API_URL + '/auth/token' + new URLSearchParams({
                username: data.email,
                password: data.password
            }), {
                method: "POST",
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })

            const loginData = await res.json()

            const token = loginData.access_token

            setError('')
            setLoading(false)

            return token
        } catch (err) {
            setError(err.message)
            setLoading(false)
            return null
        }
    }

    return { doAuth, loading, error }
}

export default useAuth