// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Difficulty, Exam} from "@/interfaces/exam";
import {Module} from "@/interfaces";
import axios from "axios";

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

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

	const params = new URLSearchParams();
	if (topic) params.append("topic", topic);
	if (exercises) (typeof exercises === "string" ? [exercises] : exercises).forEach((exercise) => params.append("exercises", exercise));
	if (difficulty) params.append("difficulty", difficulty);

	const result = await axios.get(`${url}${params.toString().length > 0 ? `?${params.toString()}` : ""}`, {
		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});

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

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