"use client";
import { Changelog } from "@repo/db";
import { ChangelogModalBtn } from "@repo/shared-components";
import { useMutation } from "@tanstack/react-query";
import { editUserAPI } from "_querys/user";
import { useSession } from "next-auth/react";
import toast from "react-hot-toast";

export const ChangelogWrapper = ({ latestChangelog }: { latestChangelog: Changelog | null }) => {
	const { data: session } = useSession();
	const editUserMutation = useMutation({
		mutationFn: editUserAPI,
	});

	const autoOpen = !session?.user.changelogAck && !!latestChangelog;

	if (!latestChangelog) return null;
	if (!session) return null;

	return (
		<ChangelogModalBtn
			hideIcon
			className="text-sm text-gray-500"
			latestChangelog={latestChangelog}
			autoOpen={autoOpen}
			onClose={async () => {
				await editUserMutation.mutateAsync({ id: session?.user.id, user: { changelogAck: true } });
				if (!session?.user.changelogAck) {
					toast.success("Changelog als gelesen markiert");
				}
			}}
		/>
	);
};
