// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs, query, where, doc, setDoc, addDoc, getDoc, deleteDoc} from "firebase/firestore";
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 = getFirestore(app);

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 q = query(collection(db, "stats"));

	const snapshot = await getDocs(q);

	res.status(200).json(
		snapshot.docs.map((doc) => ({
			id: doc.id,
			...doc.data(),
		})),
	);
}

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

	const stats = req.body as Stat[];
	await stats.forEach(async (stat) => await setDoc(doc(db, "stats", stat.id), stat));
	await stats.forEach(async (stat) => {
		const sessionDoc = await getDoc(doc(db, "sessions", stat.session));
		if (sessionDoc.exists()) await deleteDoc(sessionDoc.ref);
	});

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

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

			const assignmentSnapshot = await getDoc(doc(db, "assignments", assignmentId));
			await setDoc(
				doc(db, "assignments", assignmentId),
				{
					results: [
						...(assignmentSnapshot.data() as Assignment).results,
						{user: req.session.user?.id, type: req.session.user?.focus, stats: assignmentStats},
					],
				},
				{merge: true},
			);
		});
	}

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