import { BASE_API_URI } from '$lib/utils/constants.js';
import { refreshCookie, userDatesFromRFC3339 } from '$lib/utils/helpers';

/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
	console.log('Hook started', event.url.pathname);
	if (event.locals.user) {
		// if there is already a user  in session load page as normal
		console.log('user is logged in');
		return await resolve(event);
	}

	// get cookies from browser
	const jwt = event.cookies.get('jwt');

	if (!jwt) {
		// if there is no jwt load page as normal
		return await resolve(event);
	}
	const response = await fetch(`${BASE_API_URI}/backend/users/current`, {
		credentials: 'include',
		headers: {
			Cookie: `jwt=${jwt}`
		}
	});
	if (!response.ok) {
		// Clear the invalid JWT cookie
		event.cookies.delete('jwt', { path: '/' });
		return await resolve(event);
	}

	const data = await response.json();

	// Check if the server sent a new token
	const newToken = response.headers.get('Set-Cookie');
	refreshCookie(newToken, event.cookies);

	userDatesFromRFC3339(data.user);

	const [subscriptionsResponse, licenceCategoriesResponse] = await Promise.all([
		fetch(`${BASE_API_URI}/backend/membership/subscriptions`, {
			credentials: 'include',
			headers: { Cookie: `jwt=${jwt}` }
		}),
		fetch(`${BASE_API_URI}/backend/licence/categories`, {
			credentials: 'include',
			headers: { Cookie: `jwt=${jwt}` }
		})
	]);
	const [subscriptionsData, licence_categoriesData] = await Promise.all([
		subscriptionsResponse.json(),
		licenceCategoriesResponse.json()
	]);
	event.locals.user = data.user;
	event.locals.subscriptions = subscriptionsData.subscriptions;
	event.locals.licence_categories = licence_categoriesData.licence_categories;

	// load page as normal
	return await resolve(event);
}
