import { redirect } from '@sveltejs/kit';
import type { LayoutServerLoad } from './$types';
import {
	canWrite,
	getMenuItemsForRole,
	getRoutePermission,
	hasPermission
} from '$lib/constants/backoffice-role';

const PUBLIC_PATHS = ['/backoffice/login'];

export const load: LayoutServerLoad = async ({ locals, url }) => {
	const isPublic = PUBLIC_PATHS.includes(url.pathname);

	if (isPublic) {
		return { isPublic: true as const, backofficeUser: null, menuItems: [], canWrite: false };
	}

	if (!locals.backofficeUser) {
		throw redirect(303, '/backoffice/login');
	}

	const permission = getRoutePermission(url.pathname);
	if (permission && !hasPermission(locals.backofficeUser.role, permission)) {
		throw redirect(303, '/backoffice?error=forbidden');
	}

	return {
		isPublic: false as const,
		backofficeUser: locals.backofficeUser,
		menuItems: getMenuItemsForRole(locals.backofficeUser.role),
		canWrite: canWrite(locals.backofficeUser.role)
	};
};
