import { API_URL } from '$env/static/private';

import type { PageServerLoad } from './$types';

import type { Chapter } from '$lib/types';
import { redirect } from '@sveltejs/kit';

export const load = (async ({ parent, fetch, cookies, params: { chapterId } }) => {
	await parent();

	const session = cookies.get('session');

	const res = await fetch(`${API_URL}/chapter/${chapterId}`, {
		headers: {
			Authorization: `Bearer ${session}`
		}
	});

	if (!res.ok) {
		throw redirect(302, '/dashboard/chapters');
	}

	const chapter = (await res.json()) as Chapter;

	if (!chapter || !chapter.show) {
		throw redirect(302, '/dashboard/chapters');
	}

	return {
		chapter
	};
}) satisfies PageServerLoad;
