async function fetchPassKeyChallenge(): Promise<string> {
  return await fetch(
    `${import.meta.env.VITE_API_HOST}/user/passkey/challenge`,
    {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    }
  )
    .then(async res => {
      const data = await res.json()
      if (res.ok && data.state === 'success') {
        return data.data
      } else {
        throw new Error(data.message)
      }
    })
    .catch(err => {
      toast.error(t('auth.errorMessages.passkeyChallenge'))
      console.error(err)
    })
}

async function registerWithPasskey() {
  const res = await webauthn.client.register(
    'melvinchia623600@gmail.com',
    '20e47b44-293a-417a-8559-d7f32affd8b4',
    {
      authenticatorType: 'both',
      userVerification: 'required',
      discoverable: 'preferred',
      timeout: 60000,
      attestation: true
    }
  )

  await fetch(`${import.meta.env.VITE_API_HOST}/user/passkey/register`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(res)
  })
    .then(async res => {
      const data = await res.json()
      if (res.ok && data.state === 'success') {
        toast.success(t('auth.passkey.createSuccess'))
      } else {
        throw new Error(data.message)
      }
    })
    .catch(err => {
      toast.error(t('auth.errorMessages.passkeyRegister'))
      console.error(err)
    })
    .finally(() => {
      setLoading(false)
    })
}

async function signInWithPasskey() {
  if (
    window.PublicKeyCredential &&
    PublicKeyCredential.isConditionalMediationAvailable
  ) {
    const isCMA = await PublicKeyCredential.isConditionalMediationAvailable()
    if (!isCMA) {
      toast.error('This browser does not support passkey login')
      return
    }
  }

  setLoading(true)
  const challenge = await fetchPassKeyChallenge()

  const res = await webauthn.client.authenticate([], challenge, {
    authenticatorType: 'local'
  })

  await fetch(`${import.meta.env.VITE_API_HOST}/user/passkey/login`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(res)
  })
    .then(async res => {
      const data = await res.json()

      if (res.ok && data.state === 'success') {
        document.cookie = `session=${data.session}; path=/; expires=${new Date(
          Date.now() + 7 * 24 * 60 * 60 * 1000
        ).toUTCString()}`

        verifySession(data.session)
          .then(async ({ success, userData }) => {
            if (success) {
              setUserData(userData)
              setAuth(true)

              toast.success(t('auth.welcome') + userData.username)
            }
          })
          .catch(() => {
            setAuth(false)
          })
          .finally(() => {
            setLoading(false)
          })
      } else {
        throw new Error(data.message)
      }
    })
    .catch(err => {
      toast.error(t('auth.errorMessages.passkeyLogin'))
      console.error(err)
    })
    .finally(() => {
      setLoading(false)
    })
}
