import { getSession } from '$lib/server/session';
import { Permissions } from '$lib/permissions';
import type { RequestHandler } from '@sveltejs/kit';
import { Admin, User } from '$lib/server/database';

export const POST = (async ({ request, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.UserRead] }) == null) {
		return new Response(null, {
			status: 401
		});
	}

	const data = await request.json();
	const limit = data['limit'] || 100;
	const from = data['from'] || 0;

	const users = await User.findAll({ offset: from, limit: limit });

	return new Response(JSON.stringify(users));
}) satisfies RequestHandler;

export const PATCH = (async ({ request, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.UserWrite] }) == null) {
		return new Response(null, {
			status: 401
		});
	}

	const data = await request.json();
	const id = data['id'] as string | null;

	if (id == null) {
		return new Response(null, {
			status: 400
		});
	}

	const user = await User.findOne({ where: { id: id } });
	if (!user) {
		return new Response(null, {
			status: 400
		});
	}

	if (data['firstname']) user.firstname = data['firstname'];
	if (data['lastname']) user.lastname = data['lastname'];
	if (data['birthday']) user.birthday = data['birthday'];
	if (data['telephone']) user.telephone = data['telephone'];
	if (data['username']) user.username = data['username'];
	if (data['playertype']) user.playertype = data['playertype'];
	if (data['password']) user.password = data['password'];
	if (data['uuid']) user.uuid = data['uuid'];
	await user.save();

	return new Response();
}) satisfies RequestHandler;

export const DELETE = (async ({ request, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.UserWrite] }) == null) {
		return new Response(null, {
			status: 401
		});
	}

	const data = await request.json();
	const id = (data['id'] as number) || null;

	if (id == null) {
		return new Response(null, {
			status: 400
		});
	}

	await User.destroy({ where: { id: id } });

	return new Response();
}) satisfies RequestHandler;
