// /admin gate. The backend's RequireAdmin extractor is the actual
// security boundary — this load function just calls a tiny admin
// endpoint and translates the response into either a redirect (no
// session) or SvelteKit's framework error page (403 forbidden).
// The session.user?.is_admin check elsewhere is UX only.
//
// `ssr=false` because the session store is browser-only (see
// $lib/session.svelte.ts) — server-side load can't read the cookie
// anyway in this app's deployment shape.

import { error, redirect } from '@sveltejs/kit';
import { ApiError } from '$lib/api/client';
import { getSystemStats } from '$lib/api/admin';
import type { LayoutLoad } from './$types';

export const ssr = false;

export const load: LayoutLoad = async () => {
    try {
        const stats = await getSystemStats();
        return { stats };
    } catch (e) {
        if (e instanceof ApiError && e.status === 401) {
            throw redirect(302, '/login');
        }
        if (e instanceof ApiError && e.status === 403) {
            throw error(403, 'admin access required');
        }
        throw e;
    }
};
