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

async function user(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "GET") return get(req, res);
	if (req.method === "DELETE") return del(req, res);
	res.status(404).json(undefined);
}

async function get(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.token || !req.session.user) {
		return res.status(401).json(undefined);
	}

	try {
		const resp = await fetch(`${ODOO_URL}/api/user`, {
			headers: {Authorization: `Bearer ${req.session.token}`},
		});

		if (!resp.ok) {
			req.session.destroy();
			return res.status(401).json(undefined);
		}

		const data = await resp.json();
		const user = {...data, id: String(data.id)};

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

		res.json(user);
	} catch {
		res.status(502).json({error: "Backend unavailable"});
	}
}

async function del(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.token) {
		return res.status(401).json({ok: false});
	}

	const {id} = req.query as {id: string};

	try {
		const resp = await fetch(`${ODOO_URL}/api/users/${id}`, {
			method: "DELETE",
			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"});
	}
}
