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.session.token) return res.status(401).json({ok: false});

	const modules = Array.isArray(req.query.module) ? req.query.module : [req.query.module];
	let endpoint = modules.join("/");

	if (req.method === "GET") {
		const url = new URL(`${ODOO_URL}/api/exam/${endpoint}`);
		Object.entries(req.query).forEach(([k, v]) => {
			if (k !== "module" && v) url.searchParams.set(k, String(v));
		});

		try {
			const resp = await fetch(url.toString(), {
				headers: {Authorization: `Bearer ${req.session.token}`},
			});
			const data = await resp.json();
			return res.status(resp.status).json(data);
		} catch {
			return res.status(502).json({error: "Backend unavailable"});
		}
	}

	if (req.method === "POST") {
		if (endpoint.startsWith("level")) endpoint = "level/";
		else if (endpoint.startsWith("listening")) endpoint = "listening/";
		else if (endpoint.startsWith("reading")) endpoint = "reading/";

		const hasFiles = req.headers["content-type"]?.startsWith("multipart/form-data");
		const path = `/api/exam/${endpoint}${hasFiles ? "/attachment" : ""}`;

		const chunks: Buffer[] = [];
		for await (const chunk of req) chunks.push(Buffer.from(chunk));
		const body = Buffer.concat(chunks);

		try {
			const headers: Record<string, string> = {
				Authorization: `Bearer ${req.session.token}`,
			};
			if (req.headers["content-type"]) {
				headers["Content-Type"] = req.headers["content-type"];
			}

			const resp = await fetch(`${ODOO_URL}${path}`, {
				method: "POST",
				headers,
				body,
			});

			const contentType = resp.headers.get("content-type") || "";
			res.status(resp.status);
			res.setHeader("Content-Type", contentType);
			const buf = Buffer.from(await resp.arrayBuffer());
			return res.send(buf);
		} catch {
			return res.status(502).json({error: "Backend unavailable"});
		}
	}

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

export const config = {
	api: {
		bodyParser: false,
	},
};
