import type { Handle } from '@sveltejs/kit';

import { API_URL } from '$env/static/private';

import type { User } from '$lib/types';

export const handle = (async ({ event, resolve }) => {
	const session = event.cookies.get('session');

	if (session) {
		const res = await fetch(`${API_URL}/player/`, {
			headers: {
				Authorization: `Bearer ${session}`
			}
		});

		if (res.ok) {
			const user = (await res.json()) as User;
			event.locals.user = user;
		} else {
			event.locals.user = undefined;
			event.cookies.delete('session');
		}
	}

	return await resolve(event);
}) satisfies Handle;
