"use server";

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

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

	if (!session) {
		return {
			error: strings.ERROR.NO_SESSION,
		};
	}

	try {
		await lucia.invalidateSession(session.id);
	} catch (error) {
		return {
			error: strings.ERROR.NO_SESSION,
		};
	}

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

	revalidatePath(path ?? "/");
}
