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

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

	const data: {
		limit: number | null;
		from: number | null;

		name: string | null;
		edition: 'java' | 'bedrock' | 'cracked' | null;

		search: string | null;
		slim: boolean | null;
	} = await request.json();

	const usersFindOptions: Attributes<User> = {};
	if (data.name) {
		Object.assign(usersFindOptions, {
			[Op.or]: {
				firstname: { [Op.like]: `%${data.name}%` },
				lastname: { [Op.like]: `%${data.name}%` },
				username: { [Op.like]: `%${data.name}%` }
			}
		});
	} else if (data.search) {
		Object.assign(usersFindOptions, {
			[Op.or]: {
				username: { [Op.like]: `%${data.search}%` },
				uuid: { [Op.like]: `%${data.search}%` }
			}
		});
	}
	if (data.edition) {
		usersFindOptions.edition = data.edition;
	}
	const users = await User.findAll({
		where: usersFindOptions,
		attributes: data.slim ? ['username', 'uuid'] : undefined,
		offset: data.from || 0,
		limit: data.limit || 100
	});

	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;
