import {
	getBedrockUuid,
	getCrackedUuid,
	getJavaUuid,
	UserNotFoundError
} from '$lib/server/minecraft';
import { error, type RequestHandler } from '@sveltejs/kit';
import { User } from '$lib/server/database';

export const POST = (async ({ request }) => {
	const data = await request.formData();

	let uuid: string;
	try {
		// available playertypes are 'java', 'bedrock' and 'cracked'
		switch (data.get('playertype')) {
			case 'java':
				uuid = await getJavaUuid(data.get('username') as string);
				break;
			case 'bedrock':
				uuid = await getBedrockUuid(data.get('username') as string);
				break;
			case 'cracked':
				uuid = getCrackedUuid(data.get('username') as string);
				break;
			default:
				throw new Error(`invalid player type (${data.get('playertype')})`);
		}
	} catch (e) {
		if (e instanceof UserNotFoundError) {
			throw error(400, e.message);
		}
		console.error((e as Error).message);
		return new Response();
	}

	await User.create({
		firstname: data.get('firstname'),
		lastname: data.get('lastname'),
		birthday: data.get('birthday'),
		telephone: data.get('telephone'),
		username: data.get('username'),
		playertype: data.get('playertype'),
		password: data.get('password'),
		uuid: uuid
	});

	return new Response();
}) satisfies RequestHandler;
