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(login, sessionOptions);

async function login(req: NextApiRequest, res: NextApiResponse) {
	const {email, password} = req.body as {email: string; password: string};

	try {
		const resp = await fetch(`${ODOO_URL}/api/login`, {
			method: "POST",
			headers: {"Content-Type": "application/json"},
			body: JSON.stringify({email: email.toLowerCase(), password}),
		});

		const data = await resp.json();

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

		const statusMap: Record<string, string> = {
			active: "active",
			inactive: "disabled",
			suspended: "disabled",
		};

		const user = {
			...data.user,
			id: String(data.user.id),
			status: statusMap[data.user.status] || data.user.status || "active",
			permissions: Array.isArray(data.user.permissions) ? data.user.permissions : [],
		};

		req.session.user = user;
		req.session.token = data.token;
		await req.session.save();

		res.status(200).json({user});
	} catch (error) {
		console.error("Login error:", error);
		res.status(500).json({error: "Login failed"});
	}
}
