import type { LayoutServerLoad } from './$types';
import { Admin, Report, User } from '$lib/server/database';
import { getSession } from '$lib/server/session';
import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';

export const load: LayoutServerLoad = async ({ route, cookies }) => {
	const session = getSession(cookies);

	if (session == null && route.id != '/admin/login')
		throw redirect(302, `${env.PUBLIC_BASE_PATH}/admin/login`);

	return {
		userCount: session?.permissions.userRead() ? await User.count() : null,
		reportCount: session?.permissions.reportRead()
			? await Report.count({ where: { draft: false, status: ['none', 'review'] } })
			: null,
		adminCount: session?.permissions.adminRead() ? await Admin.count() : null,
		settingsRead: session?.permissions.settingsRead(),
		self: session
			? JSON.parse(JSON.stringify(await Admin.findOne({ where: { id: session.userId } })))
			: null
	};
};
