import { error, redirect } from '@sveltejs/kit';
import { ApiError } from '$lib/api/client';
import {
    getCollection,
    listCollectionMangas
} from '$lib/api/collections';
import { listCollectionPages } from '$lib/api/page_collections';
import type { PageLoad } from './$types';

export const ssr = false;

export const load: PageLoad = async ({ params, url }) => {
    try {
        const [collection, mangas, pages] = await Promise.all([
            getCollection(params.id),
            listCollectionMangas(params.id, { limit: 200 }),
            listCollectionPages(params.id, { limit: 200 })
        ]);
        return {
            collection,
            mangas: mangas.items,
            total: mangas.page.total,
            pages: pages.items
        };
    } catch (e) {
        if (e instanceof ApiError) {
            if (e.status === 401) {
                const next = encodeURIComponent(url.pathname);
                redirect(302, `/login?next=${next}`);
            }
            if (e.status === 404 || e.status === 403) {
                error(404, 'Collection not found');
            }
        }
        throw e;
    }
};
