// 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 { addUsersToEntity, addUserToEntity, createEntity, getEntities, getEntitiesWithRoles } from "@/utils/entities.be";
import { Entity } from "@/interfaces/entity";
import { v4 } from "uuid";
import { requestUser } from "@/utils/api";

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) {
	const user = await requestUser(req, res)
	if (!user) return res.status(401).json({ ok: false });

	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) {
	const user = await requestUser(req, res)
	if (!user) return res.status(401).json({ ok: false });

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

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

	const members = req.body.members as string[] | undefined || []
	console.log(members)

	const roles = await createEntity(entity)
	console.log(roles)

	await addUserToEntity(user.id, entity.id, roles.admin.id)
	if (members.length > 0) await addUsersToEntity(members, entity.id, roles.default.id)

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