import { invalid, redirect } from "@sveltejs/kit";
import { getUser, compareHash, createSession } from "$lib/database";
import { MIN_USERNAME_LENGTH, MAX_USERNAME_LENGTH, USERNAME_REGEX, MIN_PASSWORD_LENGTH, INVITE_KEY_PREFIX, COOKIE_NAME } from "$lib/constants";

/** @type {import('./$types').Actions} */
export const actions = {
	default: async ({ cookies, request, getClientAddress }) => {
		const session = cookies.get(COOKIE_NAME);
		if (session) throw redirect(302, "/");

		const data = await request.formData();
		const username = data.get("username");
		const password = data.get("password");

		const user = await getUser({ username }, { password: true });
		if (!user) return invalid(400, { error: "username" });

		const correctPassword = await compareHash(password, user.password);
		if (!correctPassword) return invalid(400, { error: "password" });

		cookies.set(COOKIE_NAME, await createSession(user._id, request.headers.get("x-forwarded-for") || getClientAddress()), { secure: !!process.env.PRODUCTION });
		throw redirect(302, "/");
	}
};
