import type { NextApiRequest, NextApiResponse } from "next";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import queryToURLSearchParams from "@/utils/query.to.url.params";

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 queryParams = queryToURLSearchParams(req);
	const endpoint = queryParams.getAll('module').join("/");

	queryParams.delete('module');

	const result = await axios.get(`${process.env.BACKEND_URL}/${endpoint}${Array.from(queryParams.entries()).length > 0 ? `?${queryParams.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 queryParams = queryToURLSearchParams(req);
	let endpoint = queryParams.getAll('module').join("/");
	
	if (endpoint.startsWith("level")) {
		endpoint = "level/"
	} else if (endpoint.startsWith("listening")) {
		endpoint = "listening/"
	} else if (endpoint.startsWith("reading")) {
		endpoint = "reading/"
	}

	const result = await axios.post(`${process.env.BACKEND_URL}/${endpoint}`,
		req.body,
		{
			headers: { Authorization: `Bearer ${process.env.BACKEND_JWT}` },
		},
	);

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