// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {CorporateUser, Group} from "@/interfaces/user";
import {Discount, Package} from "@/interfaces/paypal";
import {v4} from "uuid";
import {checkAccess} from "@/utils/permissions";
import {CEFR_STEPS} from "@/resources/grading";
import {getCorporateUser} from "@/resources/user";
import {getUserCorporate} from "@/utils/groups.be";
import {Grading} from "@/interfaces";
import {getGroupsForUser} from "@/utils/groups.be";
import {uniq} from "lodash";
import {getSpecificUsers, getUser} from "@/utils/users.be";
import {getGradingSystem} from "@/utils/grading.be";
import client from "@/lib/mongodb";

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

export default withIronSessionApiRoute(handler, sessionOptions);

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

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

	const gradingSystem = await getGradingSystem(req.session.user);
	return res.status(200).json(gradingSystem);
}

async function updateGrading(id: string, body: Grading) {
	if (await db.collection("grading").findOne({id})) {
		await db.collection("grading").updateOne({id}, {$set: body});
	} else {
		await db.collection("grading").insertOne({id, ...body});
	}
}

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

	if (!checkAccess(req.session.user, ["admin", "developer", "mastercorporate", "corporate"]))
		return res.status(403).json({
			ok: false,
			reason: "You do not have permission to create a new grading system",
		});

	const body = req.body as Grading;
	await updateGrading(req.session.user.id, body);

	if (req.session.user.type === "mastercorporate") {
		const groups = await getGroupsForUser(req.session.user.id);
		const participants = uniq(groups.flatMap((x) => x.participants));

		const participantUsers = await getSpecificUsers(participants);
		const corporateUsers = participantUsers.filter((x) => x?.type === "corporate") as CorporateUser[];

		await Promise.all(corporateUsers.map(async (g) => await updateGrading(g.id, body)));
	}

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