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

export const load: PageServerLoad = async ({ parent, cookies }) => {
	const { adminCount } = await parent();
	if (adminCount == null) throw redirect(302, `${env.PUBLIC_BASE_PATH}/admin`);

	let admins: (typeof Admin.prototype)[] = [];
	if (getSession(cookies, { permissions: [Permissions.AdminRead] }) != null) {
		admins = await Admin.findAll({ raw: true, attributes: { exclude: ['password'] } });
	}

	const session = getSession(cookies);
	return {
		admins: admins.map((v) => {
			const vv = JSON.parse(JSON.stringify(v));
			vv.permissions = new Permissions(v.permissions as unknown as number).asArray();

			return vv;
		}),
		id: session?.userId,
		permissions: session?.permissions.value || 0
	};
};
