<!--
	SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
	SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
	<main>
		<h1>Register</h1>
		<form @submit.prevent="register">
			<h2>User Details</h2>
			<p>
				<label>
					Username
					<input type="text" v-model="username">
				</label>
			</p>
			<h2>Authentication Method</h2>
			<p v-if="sessionStore.authenticationProvider">
				Provider: {{ sessionStore.authenticationProvider }}
				<br>Identifier: {{ sessionStore.authenticationName }}
				<br><button type="button" @click="clearProvider">Clear Method</button>
			</p>
			<p v-else>
				<LogInTelegram />
			</p>
			<p>
				<button type="submit">Register new account</button>
			</p>
		</form>
	</main>
</template>

<script setup lang="ts">
const sessionStore = useSessionStore();
const username = ref("");

async function clearProvider() {
	sessionStore.logOut();
}
async function register() {
	let session;
	try {
		session = await $fetch("/api/auth/account", {
			method: "POST",
			body: {
				name: username.value,
			},
		});
	} catch (err: any) {
		alert(err.data?.message ?? err.message);
		return;
	}
	sessionStore.update(session);
	if (session.account) {
		await navigateTo("/account/settings");
	}
}
</script>
