import { redirect, type Handle } from '@sveltejs/kit';
import { handle as authHandle } from './auth';
import { sequence } from '@sveltejs/kit/hooks';

/** Protect all routes except /auth/* (OIDC callback paths). */
const authorizationHandle: Handle = async ({ event, resolve }) => {
	const path = event.url.pathname;

	// Auth-ruter trenger ikke session-sjekk
	if (path.startsWith('/auth/') || path === '/signin') {
		return resolve(event);
	}

	const session = await event.locals.auth();
	if (!session?.user) {
		throw redirect(303, '/auth/signin');
	}

	// Sett isAdmin-flag basert på hostname (brukes av +page.svelte)
	const host = event.url.hostname;
	event.locals.isAdminHost = host === 'adm.synops.no';

	return resolve(event);
};

// Authentication first (sets up locals.auth), then authorization
export const handle: Handle = sequence(authHandle, authorizationHandle);
