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;
    try {
        const [author, mangas] = await Promise.all([
            getAuthor(params.id),
            listAuthorMangas(params.id, {
                limit: PAGE_SIZE,
                offset: (currentPage - 1) * PAGE_SIZE
            })
        ]);
        return {
            author,
            mangas: mangas.items,
            total: mangas.page.total,
            currentPage,
            pageSize: PAGE_SIZE
        };
    } catch (e) {
        // 404 surfaces as a real SvelteKit error so the framework shell
        // renders the standard not-found page instead of the route's
        // happy-path markup with undefined data.
        if (e instanceof ApiError && e.status === 404) {
            error(404, 'Author not found');
        }
        throw e;
    }
};
