import { API_URL } from '$env/static/private';
import { error, redirect, type Actions } from '@sveltejs/kit';
import type Puzzle from '$lib/components/Puzzle.svelte';
import type { PageServerLoad } from './$types';
import type { Chapter } from '$lib/types';

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

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

	if (isNaN(parseInt(puzzleId))) {
		throw redirect(303, `/dashboard/chapters/${chapterId}`);
	}

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

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

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

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

	if (!chapter.puzzles.some((puzzle) => puzzle.id === parseInt(puzzleId))) {
		throw redirect(303, `/dashboard/chapters/${chapterId}`);
	}

	res = await fetch(`${API_URL}/puzzle/${puzzleId}`, {
		headers: {
			Authorization: `Bearer ${session}`
		}
	});

	if (!res.ok) {
		throw error(404, 'Puzzle not found');
	}

	const puzzle = await res.json();

	if (!puzzle) {
		throw error(404, 'Puzzle not found');
	}

	console.log(puzzle.content);

	return {
		puzzle: puzzle as Puzzle
	};
}) satisfies PageServerLoad;

export const actions = {
	default: async (event) => {
		const { id } = event.params;

		const data = await event.request.formData();

		const res = await fetch(`${API_URL}/puzzleResponse/${id}`, {
			method: 'POST',
			headers: {
				Authorization: `Bearer ${event.cookies.get('session')}`
			},
			body: data
		});

		return {
			success: res.ok
		};

		// throw redirect(303, `/dashboard/puzzles/${id}`);

		// if (res.ok) {
		// 	const token = res.headers.get('Authorization')?.split(' ')[1];

		// 	if (!token) throw new Error('No token found');

		// 	event.cookies.set('session', token, {
		// 		path: '/'
		// 	});

		// 	throw redirect(303, '/dashboard');
		// }

		// throw redirect(303, '/sign-in');
	}
} satisfies Actions;
