import type { RequestHandler } from '@sveltejs/kit';
import { Permissions } from '$lib/permissions';
import {
	addSession,
	deleteAllUserSessions,
	deleteSession,
	getSession,
	updateAllUserSessions
} from '$lib/server/session';
import { Admin } from '$lib/server/database';
import { env as publicEnv } from '$env/dynamic/public';

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

	const data = await request.json();
	const username = data['username'] as string | null;
	const password = data['password'] as string | null;
	const permissions = data['permissions'] as number | null;

	if (username == null || password == null || permissions == null) {
		return new Response(null, {
			status: 400
		});
	}

	const admin = await Admin.create({
		username: username,
		password: password,
		permissions: new Permissions(permissions)
	});

	delete admin.dataValues.password;

	return new Response(JSON.stringify(admin), {
		status: 201
	});
}) satisfies RequestHandler;

export const PATCH = (async ({ request, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.AdminWrite] }) == 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 Admin.findOne({ where: { id: id } });
	if (!user) {
		return new Response(null, {
			status: 400
		});
	}

	if (data['username']) user.username = data['username'];
	if (data['password']) user.password = data['password'];
	if (data['permissions']) user.permissions = new Permissions(data['permissions']);
	await user.save();

	updateAllUserSessions(user.id, { permissions: user.permissions });

	return new Response();
}) satisfies RequestHandler;

export const DELETE = (async ({ request, cookies }) => {
	if (getSession(cookies, { permissions: [Permissions.AdminWrite] }) == 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 Admin.destroy({ where: { id: id } });
	deleteAllUserSessions(id);

	return new Response();
}) satisfies RequestHandler;
