import useSendWithButton from '../useSendWithButton'
import { composeTokenURL, processToken } from '../../api/token'
import { isTokenResponse } from '../../api/token/types'
import { setToken } from '../../utils/auth'

function useSignIn() {
    const { doSend, button } = useSendWithButton(
        'Мы уже знакомы',
        'Войдено',
        false,
        composeTokenURL(),
        'POST',
        false,
        isTokenResponse,
        processToken,
    )

    async function handleSignIn(formData: FormData) {
        const token = await doSend({}, {
            body: formData,
        })

        if (token !== null && token !== undefined) {
            setToken(token)

            return true
        }

        return false
    }

    return { handleSignIn, signInButton: button }
}

export default useSignIn
