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

export const POST = (async ({ request, cookies }) => {
	const data = await request.formData();
	const username = data.get('username') as string | null;
	const password = data.get('password') as string | null;

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

	if (
		env.ADMIN_USER &&
		env.ADMIN_PASSWORD &&
		username == env.ADMIN_USER &&
		password == env.ADMIN_PASSWORD
	) {
		cookies.set(
			'session',
			addSession({ id: -1, permissions: new Permissions(Permissions.allPermissions()) }),
			{
				path: `${publicEnv.PUBLIC_BASE_PATH}/admin`,
				maxAge: 60 * 60 * 24 * 90,
				httpOnly: true,
				secure: true
			}
		);
		return new Response();
	}

	const user = await Admin.findOne({ where: { username: username } });
	if (user && user.validatePassword(password)) {
		cookies.set('session', addSession(user), {
			path: `${publicEnv.PUBLIC_BASE_PATH}/admin`,
			maxAge: 60 * 60 * 24 * 90,
			httpOnly: true,
			secure: true
		});
		return new Response();
	} else {
		return new Response(null, {
			status: 401
		});
	}
}) satisfies RequestHandler;
