<!--
	SPDX-FileCopyrightText: © 2025 Hornwitser <code@hornwitser.no>
	SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
	<main>
		<h1>Log In</h1>
		<form @submit.prevent="logIn">
			<input v-model="name" type="text" placeholder="Name" required>
			<button type="submit">Log In</button>
		</form>
		<LogInTelegram v-if="authTelegramEnabled" />
		<h2 id="create-account">Create Account</h2>
		<p>If you don't have an account you may create one</p>
		<form @submit.prevent="createAccount">
			<fieldset>
				<legend>Regular Account</legend>
				<label>
					Name:
					<input v-model="createName" type="text" placeholder="Name" required />
				</label>
				<button type="submit">Create account</button>
			</fieldset>
		</form>
		<p>
			If you do not wish to deal with logins you may create an anonymous account tied to this device.
		</p>
		<fieldset>
			<legend>Anonymous Account</legend>
			<button type="button" @click="createAnonymousAccount">Create anonymous account</button>
		</fieldset>
		<pre><code>{{ result }}</code></pre>
		<pre><code>Session: {{ ({ id: sessionStore.id, account: sessionStore.account, push: sessionStore.push }) }}</code></pre>
	</main>
</template>

<script lang="ts" setup>
useHead({
	title: "Login",
});

const runtimeConfig = useRuntimeConfig();
const authTelegramEnabled = runtimeConfig.public.authTelegramEnabled;
const sessionStore = useSessionStore();
const { getSubscription, subscribe } = usePushNotification();

const name = ref("");
const result = ref("")
async function logIn() {
	try {
		result.value = await sessionStore.logIn(name.value);
		// Resubscribe push notifications if the user was subscribed before.
		const subscription = await getSubscription();
		if (subscription) {
			await subscribe();
		}
		// XXX Remove the need for this.
		await sessionStore.fetch();

	} catch (err: any) {
		console.log(err);
		console.log(err.data);
		result.value = `Server replied: ${err.statusCode} ${err.statusMessage}`;
	}
}

const createName = ref("");
async function createAccount() {
	try {
		const res = await $fetch.raw("/api/auth/account", {
			method: "POST",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded",
			},
			body: new URLSearchParams({ name: createName.value })
		});
		result.value = `Server replied: ${res.status} ${res.statusText}`;
		await sessionStore.fetch();

	} catch (err: any) {
		console.log(err);
		console.log(err.data);
		result.value = `Server replied: ${err.statusCode} ${err.statusMessage}`;
	}
}
async function createAnonymousAccount() {
	try {
		const res = await $fetch.raw("/api/auth/account", {
			method: "POST",
			headers: {
				"Content-Type": "application/x-www-form-urlencoded",
			},
		});
		result.value = `Server replied: ${res.status} ${res.statusText}`;
		await sessionStore.fetch();

	} catch (err: any) {
		console.log(err);
		console.log(err.data);
		result.value = `Server replied: ${err.statusCode} ${err.statusMessage}`;
	}
}
</script>
