import san from "sanitize-html";
import { messages } from "@server/constants";
import { isLoggedIn } from "@server/middlewareButNotReally";
import { Story } from "@models/stories";
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 replyingTo = await Review.findOne({
		_id: revid,
	})
		.populate("author", "username _id blocked")
		.exec();
	if (!replyingTo) {
		throw createError({
			statusCode: 404,
			message: messages[404],
		});
	}
	if (
		(replyingTo?.author as IUser).blocked.includes(ev.context.currentUser!._id) ||
		ev.context.currentUser!.blocked.includes((replyingTo?.author as IUser)._id)
	) {
		throw createError({
			statusCode: 403,
			message: "That didn't work",
		});
	}
	const body = await readBody(ev);
	const newReply = new Review({
		author: ev.context.currentUser!._id,
		replyingTo: revid,
		text: san(body.content),
		leftOn: replyingTo?.leftOn,
		whichChapter: replyingTo.whichChapter,
		datePosted: new Date(),
	});
	const { _id } = await newReply.save();
	const nrs = (await Review.findOne({ _id }).populate("author", "username _id blocked").exec())!;
	replyingTo.replies.push(nrs._id);
	await replyingTo.save();
	const story = await Story.findById(replyingTo.leftOn);
	if (!story) {
		throw createError({
			statusCode: 404,
		});
	}
	return {
		back: `/story/${replyingTo.leftOn}/${story!.chapters.findIndex((x) => x.id === nrs.whichChapter) + 1}`,
		data: nrs.toObject(),
		success: true,
	};
});
