<template>
  <h1>LogJensticks</h1>
  <form @submit.prevent="submit">
    <div>
      <label for="username">Username</label><br>
      <input id="username" v-model="username" type="text" required autofocus>
    </div>
    <div>
      <label for="password">Password</label><br>
      <input id="password" v-model="password" type="password" required>
    </div>
    <div>
      <button type="submit">Log In</button>
    </div>
    <p v-if="error" style="color:red">{{ error }}</p>
  </form>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const username = ref('')
const password = ref('')
const error = ref('')

async function submit() {
  error.value = ''
  const res = await fetch('/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username: username.value, password: password.value }),
  })

  if (res.ok) {
    const { data } = await res.json()
    router.push(data.role === 'broker' ? '/broker' : '/carrier')
  } else {
    error.value = 'Invalid username or password.'
  }
}
</script>
