<script setup lang="ts">
import { ref, inject } from 'vue';
import { auth_login, get_root, isErrorResponse, TokenInjectType } from '@/api';
import { useRouter } from 'vue-router';

const router = useRouter();

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

const jwt = inject<TokenInjectType>('jwt') as TokenInjectType;

async function login() {
	if (username.value === '' || password.value === '') {
		error.value = 'Username and/or Password missing';
		return;
	}
	const res = await auth_login(username.value, password.value);
	if (isErrorResponse(res)) error.value = 'Login failed: ' + res.message;
	else {
		const root = await get_root(res.jwt);
		if (isErrorResponse(root)) {
			error.value = 'Get root failed: ' + root.message;
			return;
		}
		jwt.setToken(res.jwt);
		await router.push({
			name: 'fs',
			params: { node_id: root.rootId }
		});
	}
}
</script>

<template>
	<div v-if="error !== ''" v-text="error"></div>
	<input type="email" placeholder="Email" v-model="username" />
	<input type="password" placeholder="Password" v-model="password" />
	<button @click="login()">Login</button>
</template>

<style scoped></style>
