// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {getEntities, getEntitiesWithRoles} from "@/utils/entities.be";
import {Entity} from "@/interfaces/entity";
import {v4} from "uuid";

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "GET") return await get(req, res);
	if (req.method === "POST") return await post(req, res);
}

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

	const user = req.session.user;
	const {showRoles} = req.query as {showRoles: string};

	const getFn = showRoles ? getEntitiesWithRoles : getEntities;

	if (["admin", "developer"].includes(user.type)) return res.status(200).json(await getFn());
	res.status(200).json(await getFn(user.entities.map((x) => x.id)));
}

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

	const user = req.session.user;
	if (!["admin", "developer"].includes(user.type)) {
		return res.status(403).json({ok: false});
	}

	const entity: Entity = {
		id: v4(),
		label: req.body.label,
	};

	return res.status(200).json(entity);
}
