import { FavPayload, SubPayload } from "~/lib/client/types/form/favSub";
import isLoggedIn from "~/lib/server/middlewareButNotReally/isLoggedIn";
import { User } from "~/models/user";

export default eventHandler(async (ev) => {
	isLoggedIn(ev);
	const body = await readBody<FavPayload>(ev);
	await User.findByIdAndUpdate(ev.context.currentUser!._id, {
		$pull: {
			"favs.authors": {
				$in: body.pull!.authors,
			},
			"favs.stories": {
				$in: body.pull!.stories,
			},
		},
	});
	const nu = await User.findByIdAndUpdate(
		ev.context.currentUser!._id,
		{
			$addToSet: {
				"favs.authors": {
					$each: body.pull!.authors,
				},
				"favs.stories": {
					$each: body.pull!.stories,
				},
			},
		},
		{ new: true },
	);
	return {
		success: true,
		data: nu?.favs,
	};
});
