<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>
		<pre><code>{{ result }}</code></pre>
		<pre><code>Session: {{ session }}</code></pre>
	</main>
</template>

<script lang="ts" setup>
const { data: session, refresh: sessionRefresh } = useAccountSession();
const { getSubscription, subscribe } = usePushNotification();

const name = ref("");
const result = ref("")
async function logIn() {
	try {
		const res = await $fetch.raw("/api/auth/login", {
			method: "POST",
			body: { name: name.value },
		});
		result.value = `Server replied: ${res.status} ${res.statusText}`;
		// Resubscribe push notifications if the user was subscribed before.
		const subscription = await getSubscription();
		if (subscription) {
			await subscribe();
		}
		await sessionRefresh();

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