// 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 {getEntityWithRoles} from "@/utils/entities.be";
import client from "@/lib/mongodb";
import {Entity} from "@/interfaces/entity";
import { assignRoleToUsers, deleteRole, getRole, transferRole } from "@/utils/roles.be";
import { doesEntityAllow } from "@/utils/permissions";
import { findBy } from "@/utils";
import { getUser } from "@/utils/users.be";

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

export default withIronSessionApiRoute(handler, sessionOptions);

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

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

	const user = await getUser(req.session.user.id);
	if (!user) return res.status(401).json({ ok: false })

	const { id } = req.query as { id: string };
	const {users} = req.body as {users: string[]}

	const role = await getRole(id)
	if (!role) return res.status(404).json({ok: false})

	const entity = await getEntityWithRoles(role.entityID)
	if (!entity) return res.status(404).json({ok: false})

	if (!doesEntityAllow(user, entity, "assign_to_role")) return res.status(403).json({ok: false})

	const result = await assignRoleToUsers(users, entity.id, role.id)
	return res.status(200).json({ok: result.acknowledged});
}
