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

const router = useRouter();

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

const error = ref('');

const requestOtp = ref(false);

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

async function login() {
	error.value = '';
	if (username.value === '' || password.value === '') {
		error.value = 'Email and/or Password missing';
		return;
	}
	const res = await (requestOtp.value
		? Auth.auth_login(username.value, password.value, otp.value)
		: Auth.auth_login(username.value, password.value));
	if (isErrorResponse(res)) error.value = 'Login failed: ' + res.message;
	else if ('jwt' in res) {
		const root = await FS.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 }
		});
	} else {
		error.value = '';
		requestOtp.value = true;
	}
}
</script>

<template>
	<div v-if="error !== ''" v-text="error"></div>
	<template v-if="!requestOtp">
		<input type="email" placeholder="Email" v-model="username" />
		<input type="password" placeholder="Password" v-model="password" />
		<a href="/api/auth/gitlab">Login with gitlab</a>
		<router-link to="signup">Signup instead?</router-link>
	</template>
	<template v-else>
		<div>Please input your 2 factor authentication code</div>
		<input type="text" placeholder="Code" v-model="otp" />
	</template>
	<button @click="login()">Login</button>
</template>

<style scoped></style>
