// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Stat } from "@/interfaces/user";
import { Assignment } from "@/interfaces/results";
import { groupBy } from "lodash";

const db = client.db(process.env.MONGODB_DB);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "GET") return get(req, res);
	if (req.method === "POST") return post(req, res);
}

async function get(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ ok: false });
		return;
	}
	const snapshot = await db.collection("stats").find<Stat>({}).toArray();

	res.status(200).json(snapshot);
}

async function post(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ ok: false });
		return;
	}

	const stats = req.body as Stat[];
	stats.forEach(async (stat) => await db.collection("stats").updateOne(
		{ id: stat.id },
		{ $set: stat },
		{ upsert: true }
	));
	stats.forEach(async (stat) => {
		await db.collection("sessions").deleteOne({ id: stat.session })
	});

	const groupedStatsByAssignment = groupBy(
		stats.filter((x) => !!x.assignment),
		"assignment",
	);
	if (Object.keys(groupedStatsByAssignment).length > 0) {
		const assignments = Object.keys(groupedStatsByAssignment);

		assignments.forEach(async (assignmentId) => {
			const assignmentStats = groupedStatsByAssignment[assignmentId] as Stat[];

			const assignmentSnapshot = await db.collection("assignments").findOne<Assignment>({ id: assignmentId });
			await db.collection("assignments").updateOne(
				{ id: assignmentId },
				{
					$set: {
						results: [
							...assignmentSnapshot ? assignmentSnapshot.results : [],
							{ user: req.session.user?.id, type: req.session.user?.focus, stats: assignmentStats },
						],
					}
				}
			);
		});
	}

	res.status(200).json({ ok: true });
}
