import san from "sanitize-html";
import { messages } from "@server/constants";
import { log } from "@server/logger";
import { isLoggedIn } from "@server/middlewareButNotReally";
import { Review } from "@models/stories/review";
import { IUser } from "@models/user";

export default eventHandler(async (ev) => {
	isLoggedIn(ev);
	const revid = parseInt(getRouterParam(ev, "revid")!);
	let c = await Review.findById(revid);
	if (!c) {
		throw createError({
			statusCode: 404,
			message: messages[404],
		});
	}
	log.silly(`${ev.context.currentUser!._id!} || ${c.author}`, {
		label: "what the fuck",
	});
	if ((c?.author as IUser)?._id != ev.context.currentUser?._id) {
		throw createError({
			message: messages[403],
			statusCode: 403,
		});
	}
	const body = await readBody(ev);
	await Review.findByIdAndUpdate(revid, {
		$set: {
			text: san(body.content),
		},
	});
	return {
		success: true,
		data: await Review.findById(revid)
			.populate("author", "username profile _id")
			.exec(),
	};
});
