<template>
  <div>
    <section>
      <div class="title is-4 has-text-white-ter has-text-centered">Login</div>
      <div class="control my-2">
        <input type="text" placeholder="Username"
               aria-label="Username" v-model="username" @keyup.enter="submit">
      </div>
      <div class="control my-2">
        <input type="password" placeholder="Password"
               aria-label="Password" v-model="password" @keyup.enter="submit">
      </div>
      <div class="buttons is-flex is-justify-content-end mt-5">
        <button @click="submit">Submit</button>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import store from '@/store';
import { login } from '@/api/composed';

const router = useRouter();

const username = ref('');
const password = ref('');

const submit = async () => {
  const resp = await login(username.value, password.value);
  if (!resp) throw new Error('Could not get response from login');
  if (resp.token !== null) {
    sessionStorage.setItem('jwt', JSON.stringify({ token: resp.token }));
    store.commit('setToken', resp.token);
    await router.push('/');
  }
};
</script>

<style scoped lang="stylus">

</style>
