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

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

	// Allow auth-related routes through without session check
	if (path.startsWith('/auth/') || path === '/signin') {
		return resolve(event);
	}

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

	return resolve(event);
};

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