// 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, getEntity, getEntityWithRoles} from "@/utils/entities.be";
import {Entity} from "@/interfaces/entity";
import {v4} from "uuid";
import { createRole, getRoles, getRolesByEntity } from "@/utils/roles.be";
import { mapBy } from "@/utils";
import { RolePermission } from "@/resources/entityPermissions";
import { doesEntityAllow } from "@/utils/permissions";
import { User } from "@/interfaces/user";
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 });

	if (["admin", "developer"].includes(user.type)) return res.status(200).json(await getRoles());
	res.status(200).json(await getRoles(mapBy(user.entities, 'role')));
}

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

	const {entityID, label, permissions} = req.body as {entityID: string, label: string, permissions: RolePermission[]}

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

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

	const role = {
		id: v4(),
		entityID,
		label,
		permissions
	}

	await createRole(role)
	return res.status(200).json(role);
}
