import { error, redirect } from '@sveltejs/kit';
import { ApiError } from '$lib/api/client';
import { getManga } from '$lib/api/mangas';
import { listChapters } from '$lib/api/chapters';
import type { PageLoad } from './$types';

export const ssr = false;

export const load: PageLoad = async ({ params, url }) => {
    try {
        // Need the manga (so we can show title + cover for context)
        // and existing chapters so we can default the chapter-number
        // field to "next available" — saves the uploader a click.
        const [manga, chapters] = await Promise.all([
            getManga(params.id),
            listChapters(params.id, { limit: 200 })
        ]);
        // The chapter list endpoint sorts by number ASC; the next
        // suggested number is one more than the largest. 200 covers
        // every realistic series; users with more chapters can edit
        // the number manually.
        const maxNumber = chapters.items.reduce(
            (max, c) => Math.max(max, c.number),
            0
        );
        return { manga, defaultNumber: maxNumber + 1 };
    } catch (e) {
        if (e instanceof ApiError && e.status === 401) {
            redirect(302, `/login?next=${encodeURIComponent(url.pathname)}`);
        }
        if (e instanceof ApiError && e.status === 404) {
            error(404, 'Manga not found');
        }
        throw e;
    }
};
