import { type Actions, fail, error } from "@sveltejs/kit";
import { auth } from "$lib/server/lucia";
import { redirect } from "@sveltejs/kit";
import { client } from "$lib/server/lucia";

export const load = async ({ locals }) => {
	const { user } = await locals.auth.validateUser();
	if (!user) throw redirect(302, "/login");
	return {
		user
	};
};

export const actions: Actions = {
	signOut: async ({ locals }) => {
		const session = await locals.auth.validate();
		if (!session) return fail(401);
		await auth.invalidateSession(session.sessionId); // invalidate session
		locals.auth.setSession(null); // remove cookie
		throw redirect(302, '/');
	},

	deleteUser: async ({ locals }) => {
		const { user } = await locals.auth.validateUser();
		if (!user) return fail(401);
		
		try {
			const prisma = client;
			await prisma.authPost.deleteMany({
				where: {
					author_id: user.userId
				}
			})
			await auth.deleteUser(user.userId);

		} catch (e) {
			throw error(500);
		}
		throw redirect(302, '/');
	}
};