import { isIdNan } from "@server/middlewareButNotReally";
import { Story } from "@models/stories";

export default eventHandler(async (ev) => {
	const id = isIdNan(ev);
	const ip = getRequestIP(ev, { xForwardedFor: true });
	const storage = useStorage(`/stories/story/${id}/viewMap`);
	if (ev.context.currentUser) {
		if (!(await storage.hasItem(`loggedIn/${ev.context.currentUser._id}`))) {
			await Story.findByIdAndUpdate(id, {
				$inc: {
					views: 1,
				},
			});
		}
		await storage.setItem(`loggedIn/${ev.context.currentUser._id}`, Date.now());
	} else if (!!ip) {
		if (!(await storage.hasItem(`/loggedIn/${ip}`))) {
			await Story.findByIdAndUpdate(id, {
				$inc: {
					views: 1,
				},
			});
		}
		await storage.setItem(ip, Date.now());
	}
	return {};
});
