import { ApiError } from '$lib/api/client';
import { listMyPageTags, listMyDistinctPageTags } from '$lib/api/page_tags';
import type { PageLoad } from './$types';

export const ssr = false;

// Desktop home for the user's page tags — the parity counterpart to the
// mobile Library "Page tags" tab. Loads the same data the library wrapper
// feeds PageTagsList. 401 → unauthenticated path; the page shows a sign-in
// prompt.
export const load: PageLoad = async () => {
    try {
        const [pageTags, distinctPageTags] = await Promise.all([
            listMyPageTags({ limit: 100 }),
            listMyDistinctPageTags(undefined, 100)
        ]);
        return {
            authenticated: true,
            pageTags: pageTags.items,
            distinctPageTags,
            error: null as string | null
        };
    } catch (e) {
        if (e instanceof ApiError && e.status === 401) {
            return { authenticated: false, pageTags: [], distinctPageTags: [], error: null };
        }
        if (e instanceof ApiError) {
            return { authenticated: true, pageTags: [], distinctPageTags: [], error: e.message };
        }
        throw e;
    }
};
