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

export const ssr = false;

export const load: PageLoad = async () => {
    // Streamed so the grid shows a skeleton while the single fetch (also the
    // auth gate) is in flight.
    return {
        result: (async () => {
            try {
                const page = await listMyCollections({ limit: 200 });
                return { collections: page.items, authenticated: true, error: null as string | null };
            } catch (e) {
                if (e instanceof ApiError && e.status === 401) {
                    return { collections: [], authenticated: false, error: null as string | null };
                }
                // An HTTP error or a raw network failure (a non-ApiError
                // TypeError) renders inline rather than escaping to the
                // framework error page for a transient API blip.
                const message = e instanceof ApiError ? e.message : 'Something went wrong.';
                return { collections: [], authenticated: true, error: message };
            }
        })()
    };
};
