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

export default withIronSessionApiRoute(register, sessionOptions);

async function register(req: NextApiRequest, res: NextApiResponse) {
	try {
		const resp = await fetch(`${ODOO_URL}/api/register`, {
			method: "POST",
			headers: {"Content-Type": "application/json"},
			body: JSON.stringify(req.body),
		});

		const data = await resp.json();

		if (!resp.ok) {
			return res.status(resp.status).json(data);
		}

		if (data.user && data.token) {
			const user = {
				...data.user,
				id: String(data.user.id),
			};
			req.session.user = user;
			req.session.token = data.token;
			await req.session.save();
			return res.status(200).json({user});
		}

		return res.status(200).json(data);
	} catch (error) {
		console.error("Registration error:", error);
		res.status(500).json({error: "Registration failed"});
	}
}
