// 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} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {shuffle} from "lodash";
import {Exam} from "@/interfaces/exam";
import {Stat} from "@/interfaces/user";
import {Module} from "@/interfaces";
import axios from "axios";

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);

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

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

	const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
	const url = `${process.env.BACKEND_URL}/${endpoint}`;

	const result = await axios.get(`${url}${topic && exercises ? `?topic=${topic.toLowerCase()}&exercises=${exercises.join("&exercises=")}` : ""}`, {
		headers: {Authorization: `Bearer ${process.env.BACKEND_JWT}`},
	});

	res.status(200).json(result.data);
}

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

	const {endpoint, topic, exercises} = req.query as {module: Module; endpoint: string; topic?: string; exercises?: string[]};
	const url = `${process.env.BACKEND_URL}/${endpoint}`;

	const result = await axios.post(
		`${url}${topic && exercises ? `?topic=${topic.toLowerCase()}&exercises=${exercises.join("&exercises=")}` : ""}`,
		req.body,
		{
			headers: {Authorization: `Bearer ${process.env.BACKEND_JWT}`},
		},
	);

	res.status(200).json(result.data);
}
