// 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 { deleteRole, getRole, transferRole } from "@/utils/roles.be";
import { doesEntityAllow } from "@/utils/permissions";
import { findBy } from "@/utils";
import { requestUser } from "@/utils/api";

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);
	if (req.method === "DELETE") return await del(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 {id} = req.query as {id: string};

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

	res.status(200).json(role);
}

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

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

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

	if (role.isDefault) return res.status(403).json({ok: false})

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

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

	const defaultRole = findBy(entity.roles, 'isDefault', true)!

	await transferRole(role.id, defaultRole.id)
	await deleteRole(role.id)

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

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

	const { id } = req.query as { id: string };
	const {label, permissions} = req.body as {label?: string, permissions?: 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, "rename_entity_role") && !!label) return res.status(403).json({ok: false})
	if (!doesEntityAllow(user, entity, "edit_role_permissions") && !!permissions) return res.status(403).json({ok: false})

	if (!!label) await db.collection<Entity>("roles").updateOne({ id }, { $set: {label} });
	if (!!permissions) await db.collection<Entity>("roles").updateOne({ id }, { $set: {permissions} });

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