import { error, fail, redirect } from "@sveltejs/kit";
import { auth } from "$lib/server/lucia";
import type { PageServerLoad, Actions } from "./$types";
import { ZodError, z } from "zod";

export const load: PageServerLoad = async ({ locals }) => {
	const session = await locals.auth.validate();
	if (session) throw redirect(302, "/");
};

const registerSchema = z.object({
	username: z.string({ required_error: 'Username is required.' })
		.min(3, { message: 'Your username must be at least 3 characters long.' })
		.max(12, { message: 'Username is too long. Limit is 12 characters.' }).trim()
		.regex(/^\w+$/, {
			message: 'Username must be a single word.',
		}),
	password: z.string({ required_error: 'Password is required.' })
		.min(3, { message: 'Your password must be at least 3 characters long.' })
		.max(25, { message: 'Password is too long. Limit is 25 characters.' }).trim()
})

export const actions: Actions = {
	default: async ({ request, locals }) => {
		const form = Object.fromEntries(await request.formData());

		try {
			const zform = registerSchema.parse(form);
			const user = await auth.createUser({
				primaryKey: {
					providerId: "username",
					providerUserId: zform.username,
					password: zform.password
				},
				attributes: {
					username: zform.username
				}
			});
			const session = await auth.createSession(user.userId);
			locals.auth.setSession(session);

		} catch (e: any) {
			if (e instanceof ZodError) {
				const { fieldErrors: errors } = e.flatten();
				return fail(422, { errors });
			}

			else {
				const message = e.message;

				if (message.includes("Unique constraint failed on the fields: (`username`)")) {
					const errors = {
						username: ['This username is already taken.']
					};
					return fail(422, { errors })
				}
				else {
					throw error(500, { message: "Server-side mistake while signup." })
				}
			}
		}
		throw redirect(302, '/');
	},
};