import { listMyBookmarks } from '$lib/api/bookmarks';
import { ApiError } from '$lib/api/client';
import type { PageLoad } from './$types';

export const ssr = false;

export const load: PageLoad = async () => {
    // Streamed (the load itself doesn't await) so the list shows a skeleton
    // while the single fetch — which is also the auth gate — is in flight.
    return {
        result: (async () => {
            try {
                const page = await listMyBookmarks();
                return { bookmarks: page.items, authenticated: true, error: null as string | null };
            } catch (e) {
                if (e instanceof ApiError && e.status === 401) {
                    return { bookmarks: [], authenticated: false, error: null as string | null };
                }
                // Anything else — an HTTP error (502 upstream_unavailable from
                // a backend restart, 500 internal_error) or a raw network
                // failure (a non-ApiError TypeError) — renders inline rather
                // than re-thrown: SvelteKit's generic error.html is not the
                // right UX for a transient API blip and the user is already
                // authenticated as far as we know.
                const message = e instanceof ApiError ? e.message : 'Something went wrong.';
                return { bookmarks: [], authenticated: true, error: message };
            }
        })()
    };
};
