import type { PageServerLoad } from './$types';
import { getSession } from '$lib/server/session';
import { Permissions } from '$lib/permissions';
import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';
import { Settings } from '$lib/server/database';

export const load: PageServerLoad = async ({ parent, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.SettingsRead] }) == null) {
		throw redirect(302, `${env.PUBLIC_BASE_PATH}/admin`);
	}

	const { self } = await parent();

	const settings = (await Settings.findAll()).reduce(
		(prev, curr) => {
			return { ...prev, [curr.key]: curr.value };
		},
		// eslint-disable-next-line @typescript-eslint/no-explicit-any
		{} as { [key: string]: any }
	);

	return {
		settings: {
			register: {
				enabled: settings['register.enabled'] ?? true
			}
		},
		self: self
	};
};
