// 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 {getEntity, getEntityWithRoles} from "@/utils/entities.be";
import client from "@/lib/mongodb";
import {Entity} from "@/interfaces/entity";

const db = client.db(process.env.MONGODB_DB);

export default withIronSessionApiRoute(handler, sessionOptions);

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

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

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

	const entity = await (!!showRoles ? getEntityWithRoles : getEntity)(id);
	res.status(200).json(entity);
}

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

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

	const user = req.session.user;
	if (!user.entities.map((x) => x.id).includes(id)) {
		return res.status(403).json({ok: false});
	}

	const entity = await db.collection<Entity>("entities").updateOne({id}, {$set: {label: req.body.label}});

	return res.status(200).json({ok: entity.acknowledged});
}
