"use server";
import { prisma } from "@repo/db";
import { getServerSession } from "../../api/auth/[...nextauth]/auth";

export async function getLatestChangelog() {
	try {
		const latestChangelog = await prisma.changelog.findMany({
			orderBy: {
				createdAt: "desc",
			},
			take: 1,
		});

		if (latestChangelog.length > 0 && latestChangelog[0]) {
			return {
				title: latestChangelog[0].title,
				text: latestChangelog[0].text,
				previewImage: latestChangelog[0].previewImage || "",
			};
		}

		return null;
	} catch (error) {
		console.error("Failed to fetch latest changelog:", error);
		throw new Error("Failed to fetch latest changelog");
	}
}

export async function updateChangelogAck() {
	const session = await getServerSession();
	if (session?.user) {
		await prisma.user.update({
			where: { id: session.user.id },
			data: { changelogAck: true },
		});
	}
}
