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

export const ssr = false;

/** First-page size; "Load more" pulls further pages of the same size.
 *  Not exported — SvelteKit only allows specific `+page.ts` exports. */
const COLLECTIONS_PAGE_SIZE = 60;

export const load: PageLoad = async () => {
    // Streamed so the grid shows a skeleton while the single fetch (also the
    // auth gate) is in flight.
    return {
        pageSize: COLLECTIONS_PAGE_SIZE,
        result: (async () => {
            try {
                const page = await listMyCollections({ limit: COLLECTIONS_PAGE_SIZE, offset: 0 });
                return {
                    collections: page.items,
                    total: page.page.total,
                    authenticated: true,
                    error: null as string | null
                };
            } catch (e) {
                if (e instanceof ApiError && e.status === 401) {
                    return {
                        collections: [],
                        total: 0,
                        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: [], total: 0, authenticated: true, error: message };
            }
        })()
    };
};
