import { getManga } from '$lib/api/mangas';
import { getChapter, getChapterPages, listChapters } from '$lib/api/chapters';
import { getMyReadProgressForManga } from '$lib/api/read_progress';
import type { PageLoad } from './$types';

export const ssr = false;

export const load: PageLoad = async ({ params, url }) => {
    const [manga, chapter, pages, readProgress, chapterList] = await Promise.all([
        getManga(params.id),
        getChapter(params.id, params.chapter_id),
        getChapterPages(params.id, params.chapter_id),
        // `null` for guests or first-time openers — the reader uses
        // this to seed its session-local high-water mark.
        getMyReadProgressForManga(params.id),
        // Loaded so the reader can compute prev/next chapter for the
        // chevron-driven chapter navigation. limit=200 covers every
        // realistic series; mangas with more chapters will lose some
        // chapter-jump precision at the tail edge but the in-page
        // navigation still works fine.
        listChapters(params.id, { limit: 200 })
    ]);
    return {
        manga,
        chapter,
        pages,
        readProgress,
        chapters: chapterList.items,
        // `?page=N` lets the prev-chapter chevron land directly on the
        // last page of the chapter it just navigated to. `last` is a
        // convenience sentinel for "however many pages this chapter
        // has"; numeric values are clamped to the chapter's page
        // count in the component.
        requestedPage: parsePageQuery(url.searchParams.get('page'))
    };
};

function parsePageQuery(raw: string | null): number | 'last' | null {
    if (!raw) return null;
    if (raw === 'last') return 'last';
    const n = Number(raw);
    return Number.isFinite(n) && n >= 1 ? Math.floor(n) : null;
}
