import { error } from '@sveltejs/kit';
import { ApiError } from '$lib/api/client';
import { getAuthor, listAuthorMangas } from '$lib/api/authors';
import type { PageLoad } from './$types';

export const ssr = false;

const PAGE_SIZE = 50;

export const load: PageLoad = async ({ params, url }) => {
    const pageParam = Number(url.searchParams.get('page') ?? '1');
    const currentPage =
        Number.isFinite(pageParam) && pageParam >= 1 ? Math.floor(pageParam) : 1;
    let author;
    try {
        // Awaited so a 404 surfaces as a real SvelteKit error (the framework
        // not-found page) rather than the happy-path markup with undefined
        // data. The author header is cheap, so blocking on it is fine.
        author = await getAuthor(params.id);
    } catch (e) {
        if (e instanceof ApiError && e.status === 404) {
            error(404, 'Author not found');
        }
        throw e;
    }
    return {
        author,
        // Streamed (not awaited) so the grid shows a MangaGridSkeleton while it
        // loads instead of the whole page blocking on it.
        mangas: listAuthorMangas(params.id, {
            limit: PAGE_SIZE,
            offset: (currentPage - 1) * PAGE_SIZE
        }).then((m) => ({ items: m.items, total: m.page.total })),
        currentPage,
        pageSize: PAGE_SIZE
    };
};
