import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {ODOO_URL} from "@/lib/odoo";

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method !== "POST") return res.status(404).json({ok: false});
	if (!req.session.token) return res.status(401).json({ok: false});

	const examModule = req.query.module as string;

	try {
		const resp = await fetch(`${ODOO_URL}/api/exam/${examModule}`, {
			method: "POST",
			headers: {
				Authorization: `Bearer ${req.session.token}`,
				"Content-Type": req.headers["content-type"] || "application/json",
			},
			body: typeof req.body === "object" ? JSON.stringify(req.body) : req.body,
		});

		const data = await resp.json();
		return res.status(resp.status).json(data);
	} catch {
		return res.status(502).json({error: "Backend unavailable"});
	}
}
