<script setup lang="ts">
import { AuthApiClient } from '@/api/auth';
import { ApiError } from '@/api/base';
import { useAuthStore } from '@/stores/auth-store';
import { showAlert } from '@/util/alert';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const apiClient = new AuthApiClient()

const username = ref('')
const password = ref('')
const disableForm = ref(false)

async function doLogin() {
  disableForm.value = true
  try {
    const token = await apiClient.login(username.value, password.value)
    authStore.onUserLoggedIn(username.value, token)
    if ('next' in route.query && typeof (route.query.next) === 'string') {
      await router.replace(route.query.next)
    } else {
      await router.replace('/')
    }
  } catch (err) {
    if (err instanceof ApiError) {
      await showAlert(err.message)
    } else {
      await showAlert('Request failed: ' + JSON.stringify(err))
    }
  } finally {
    disableForm.value = false
  }
}

function generateSampleData() {
  fetch('http://localhost:8080/api/sample-data', {
    method: 'POST'
  })
}
</script>
<template>
  <div>
    <h1>Login</h1>
    <form @submit.prevent="doLogin()">
      <div>
        <label for="username-input">Username</label>
        <input id="username-input" type="text" v-model="username" :disabled="disableForm" />
      </div>
      <div>
        <label for="password-input">Password</label>
        <input id="password-input" type="password" v-model="password" :disabled="disableForm" />
      </div>
      <div>
        <button type="submit" :disabled="disableForm">Login</button>
      </div>
    </form>

    <div>
      <button type="button" @click="generateSampleData()">Generate Sample Data</button>
    </div>
  </div>
</template>
