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 modules = Array.isArray(req.query.module) ? req.query.module : [req.query.module];
	const endpoint = modules[0];

	try {
		const resp = await fetch(`${ODOO_URL}/api/exam/${endpoint}/media`, {
			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 contentType = resp.headers.get("content-type") || "";

		if (contentType.includes("audio")) {
			const buf = Buffer.from(await resp.arrayBuffer());
			res.writeHead(200, {
				"Content-Type": contentType,
				"Content-Length": buf.length,
			});
			return res.end(buf);
		}

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