import mongoose from "mongoose";
import { Story } from "~/models/stories";
import { User } from "~/models/user";

let authorSingleton: {
	lastRefreshed: number;
	data: {
		username: string;
		_id: number;
		numStories: number;
	}[];
} = {
	data: [],
	lastRefreshed: Date.now(),
};

const threshold = 60 * 60 * 1000;

export default cachedEventHandler(
	async (event) => {
		let aa = mongoose.connection.db.collection("z_index_totAuthors");
		let totalStories = await Story.countDocuments({ "chapters.hidden": false });
		if (
			!authorSingleton.data.length ||
			Date.now() - authorSingleton.lastRefreshed >= threshold
		) {
			authorSingleton.data = await User.aggregate([
				{ $project: { username: true, _id: true } },
				{
					$lookup: {
						from: "stories",
						localField: "_id",
						foreignField: "author",
						as: "stories",
					},
				},
				{ $set: { numStories: { $size: "$stories" } } },
				{ $unset: "stories" },
				{ $match: { numStories: { $gte: 1 } } },
			]);
		}
		let totalAuthors = authorSingleton.data.length;

		return { stories: totalStories, authors: totalAuthors };
	},
	{ maxAge: 60 * 60 * 24 },
);