// 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, setDoc, doc, getDoc, deleteDoc, query} from "firebase/firestore";
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 {getUser} from "@/utils/users.be";

const db = getFirestore(app);

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 snapshot = await getDoc(doc(db, "grading", req.session.user.id));
	if (snapshot.exists()) return res.status(200).json(snapshot.data());

	if (req.session.user.type !== "teacher" && req.session.user.type !== "student")
		return res.status(200).json({steps: CEFR_STEPS, user: req.session.user.id});

	const corporate = await getUserCorporate(req.session.user.id);
	if (!corporate) return res.status(200).json(CEFR_STEPS);

	const corporateSnapshot = await getDoc(doc(db, "grading", corporate.id));
	if (corporateSnapshot.exists()) return res.status(200).json(snapshot.data());

	return res.status(200).json({steps: CEFR_STEPS, user: req.session.user.id});
}

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 setDoc(doc(db, "grading", 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 Promise.all(participants.map(getUser));
		const corporateUsers = participantUsers.filter((x) => x.type === "corporate") as CorporateUser[];

		await Promise.all(corporateUsers.map(async (g) => await setDoc(doc(db, "grading", g.id), body)));
	}

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