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

	try {
		const resp = await fetch(`${ODOO_URL}/api/exam/listening/instructions`, {
			method: "POST",
			headers: {
				Authorization: `Bearer ${req.session.token}`,
				"Content-Type": "application/json",
			},
			body: JSON.stringify(req.body),
		});

		const buf = Buffer.from(await resp.arrayBuffer());
		res.writeHead(200, {
			"Content-Type": "audio/mpeg",
			"Content-Length": buf.length,
		});
		res.end(buf);
	} catch {
		res.status(502).json({error: "Backend unavailable"});
	}
}
