// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, setDoc, doc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Exam} from "@/interfaces/exam";
import { getExams } from "@/utils/exams.be";
const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

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

	res.status(404).json({ok: false});
}

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

	const {
		module,
		avoidRepeated,
	} = req.query as {module: string; avoidRepeated: string};

	const exams: Exam[] = await getExams(db, module, avoidRepeated, req.session.user.id);
	res.status(200).json(exams);
}

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

	if (req.session.user.type !== "developer") {
		res.status(403).json({ok: false});
		return;
	}
	const {module} = req.query as {module: string};

	const exam = {...req.body, module: module};
	await setDoc(doc(db, module, req.body.id), exam);

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