// 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 {Session} from "@/hooks/useSessions";
import moment from "moment";

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 {user} = req.query as {user?: string};

	const q = user ? {user: user} : {};
	const sessions = await db.collection("sessions").find<Session>(q).limit(10).toArray();

	res.status(200).json(
		sessions.filter((x) => {
			if (!x.assignment) return true;
			if (x.assignment.results.filter((y) => y.user === user).length > 0) return false;
			return !moment().isAfter(moment(x.assignment.endDate));
		}),
	);
}

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

	await db.collection("sessions").updateOne({id: session.id}, {$set: session}, {upsert: true});

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