import type { PageData } from './$types';
import type { RequestHandler } from '@sveltejs/kit';
import { getSession } from '$lib/server/session';
import { Permissions } from '$lib/permissions';
import { Settings } from '$lib/server/database';

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

	const settings: PageData['settings'] = await request.json();

	for (const [key, value] of Object.entries(settings.register)) {
		const setting = await Settings.findOne({ where: { key: `register.${key}` } });
		if (setting) {
			setting.value = JSON.stringify(value);
			await setting.save();
		} else {
			await Settings.create({
				key: `register.${key}`,
				value: JSON.stringify(value)
			});
		}
	}

	return new Response();
}) satisfies RequestHandler;
