import type { Handle } from '@sveltejs/kit';
import {
	BACKOFFICE_SESSION_COOKIE,
	parseBackofficeSessionToken,
	parseSessionToken,
	SESSION_COOKIE
} from '$lib/server/auth';
import { findBackofficeSessionById } from '$lib/server/backoffice-user';

export const handle: Handle = async ({ event, resolve }) => {
	const memberToken = event.cookies.get(SESSION_COOKIE);
	event.locals.member = memberToken ? parseSessionToken(memberToken) : null;

	const backofficeToken = event.cookies.get(BACKOFFICE_SESSION_COOKIE);
	if (backofficeToken) {
		const parsed = parseBackofficeSessionToken(backofficeToken);
		if (parsed) {
			const fresh = await findBackofficeSessionById(parsed.id);
			event.locals.backofficeUser = fresh;
		} else {
			event.locals.backofficeUser = null;
		}
	} else {
		event.locals.backofficeUser = null;
	}

	return resolve(event);
};
