"use server";

import { lucia, validateRequest } from "@/server/auth";
import { AuthenticationError } from "@/utils/errors";
import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";

export async function logout(path?: string) {
	const { session } = await validateRequest();

	if (!session) {
		throw new AuthenticationError();
	}

	try {
		await lucia.invalidateSession(session.id);
	} catch (error) {
		throw new AuthenticationError();
	}

	const sessionCookie = lucia.createBlankSessionCookie();
	cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);

	revalidatePath(path ?? "/");
}
