import { sequelize } from '$lib/server/database';
import type { Handle } from '@sveltejs/kit';
import { env } from '$env/dynamic/public';
import { getSession } from '$lib/server/session';

// make sure that the database and tables exist
await sequelize.sync();

export const handle: Handle = async ({ event, resolve }) => {
	if (
		event.url.pathname.startsWith(`${env.PUBLIC_BASE_PATH}/admin`) &&
		event.url.pathname != `${env.PUBLIC_BASE_PATH}/admin/login`
	) {
		if (getSession(event.cookies.get('session') || '') == null) {
			return new Response(null, {
				status: 302,
				headers: {
					location: `${env.PUBLIC_BASE_PATH}/admin/login`
				}
			});
		}
	}

	return resolve(event);
};
