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

// If the user exists, redirect authenticated users to the profile page.
export const load: PageServerLoad = async ({ locals }) => {
	const session = await locals.auth.validate();
	if (session) throw redirect(302, "/");
};

const loginSchema = 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(),
	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 = loginSchema.parse(form);
			// reference the user where
			// their id is "zform.username"
			// when using "username" auth method
			// and check their password
			const key = await auth.useKey("username", zform.username, zform.password);
			const session = await auth.createSession(key.userId);
			locals.auth.setSession(session);

		} catch (e: any) {
			if (e instanceof LuciaError) {
				const message = e.message;

				if (message == "AUTH_INVALID_KEY_ID") {
					const errors = {
						username: ['This username does not exist!']
					};
					return fail(422, { errors })
				}
				else if (message == "AUTH_INVALID_PASSWORD") {
					const errors = {
						password: ['Incorrect password!']
					};
					return fail(422, { errors })
				}
				else {
					throw error(500, { message: "Server-side mistake while signin in instanceof LuciaError." })
				}
			}

			const { fieldErrors: errors } = e.flatten();
			return fail(422, { errors });
		}
		throw redirect(302, '/');
	},
};