<script setup lang="ts">
import { AuthenticationAPIClient } from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import { ref, type Ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface Credentials {
  username: string
  password: string
}

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const credentials: Ref<Credentials> = ref({ username: '', password: '' })
const apiClient = new AuthenticationAPIClient(authStore)

async function doLogin() {
  const user = await apiClient.login(credentials.value.username, credentials.value.password).handleErrorsWithAlert()
  if (user) {
    authStore.logIn(credentials.value.username, credentials.value.password, user)
    if ('next' in route.query && typeof (route.query.next) === 'string') {
      await router.replace(route.query.next)
    } else {
      await router.replace('/')
    }
  }
}
</script>
<template>
  <main>
    <h1>Login</h1>
    <form>
      <div>
        <label for="username-input">Username</label>
        <input id="username-input" name="username" type="text" v-model="credentials.username" />
      </div>
      <div>
        <label for="password-input">Password</label>
        <input id="password-input" name="password" type="password" v-model="credentials.password" />
      </div>
      <div class="button-bar">
        <button type="button" @click="doLogin">Login</button>
      </div>
      <div>
        <p>
          If you forgot your password or would like to create an account, please contact <a
            href="https://andrewlalis.com/contact">Andrew Lalis</a> for assistance.
        </p>
        <p>
          For security purposes, refreshing this site or closing your browser will log you out.
        </p>
      </div>
    </form>
  </main>
</template>
