import { API_URL } from '$env/static/private';
import { error, redirect, type Actions, fail } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

import type Puzzle from '$lib/components/Puzzle.svelte';
import type { Chapter } from '$lib/types';

import { superValidate } from 'sveltekit-superforms/server';
import { z } from 'zod';

const puzzleSchema = z.object({
	// answer: z.string().trim(),
	// answer need to be filled
	answer: z
		.string({
			required_error: 'Réponse manquante'
		})
		.refine((val) => val.trim() !== '', {
			message: 'Réponse manquante'
		}),
	file: z.any().optional()
});

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');
	}

	return {
		puzzle: puzzle as Puzzle,
		url: `${API_URL}/puzzleResponse/${puzzleId}`,
		session
	};
}) satisfies PageServerLoad;

export const actions = {
	default: async ({ params, request, cookies }) => {
		throw redirect(303, `/dashboard/chapters/${params.chapterId}/puzzle/${params.puzzleId}`);
	}
} satisfies Actions;
