// 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 {countEntityUsers, getEntityUsers} from "@/utils/users.be";
import client from "@/lib/mongodb";

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, onlyCount} = req.query as {id: string; onlyCount: string};

	if (onlyCount) return res.status(200).json(await countEntityUsers(id));

	const users = await getEntityUsers(id);
	res.status(200).json(users);
}

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 {add, members, role} = req.body as {add: boolean; members: string[]; role?: string};

	if (add) {
		await db.collection("users").updateMany(
			{id: {$in: members}},
			{
				// @ts-expect-error
				$push: {
					entities: {id, role},
				},
			},
		);

		return res.status(204).end();
	}

	await db.collection("users").updateMany(
		{id: {$in: members}},
		{
			// @ts-expect-error
			$pull: {
				entities: {id},
			},
		},
	);

	return res.status(204).end();
}
