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 === "POST") return post(req, res);

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


async function post(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("/");

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