import { json } from '@sveltejs/kit';
import { getLieuById, scoreGuess, skipResult } from '$lib/server/lieux';
import type { RequestHandler } from './$types';

interface GuessBody {
	id?: unknown;
	lat?: unknown;
	lon?: unknown;
	hintsUsed?: unknown;
	timeMs?: unknown;
	skip?: unknown;
}

/**
 * POST /api/guess { id, lat, lon, hintsUsed, timeMs? }
 * → score recalculé serveur + vérité du lieu (révélée seulement ici).
 * `skip: true` révèle la réponse avec un score de 0 (bouton « Passer »).
 */
export const POST: RequestHandler = async ({ request }) => {
	let body: GuessBody;
	try {
		body = (await request.json()) as GuessBody;
	} catch {
		return json({ erreur: 'Corps JSON invalide' }, { status: 400 });
	}

	if (typeof body.id !== 'string') {
		return json({ erreur: 'id manquant' }, { status: 400 });
	}
	const lieu = getLieuById(body.id);
	if (!lieu) {
		return json({ erreur: 'Lieu inconnu' }, { status: 404 });
	}

	if (body.skip === true) {
		return json(skipResult(lieu));
	}

	const lat = Number(body.lat);
	const lon = Number(body.lon);
	if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
		return json({ erreur: 'Coordonnées invalides' }, { status: 400 });
	}
	const hintsUsed = Math.max(0, Math.floor(Number(body.hintsUsed) || 0));
	const timeMs =
		typeof body.timeMs === 'number' && Number.isFinite(body.timeMs) && body.timeMs >= 0
			? body.timeMs
			: undefined;

	return json(scoreGuess(lieu, { lat, lon }, hintsUsed, timeMs));
};
