// 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 { deleteEntity, getEntity, getEntityWithRoles } from "@/utils/entities.be";
import client from "@/lib/mongodb";
import { Entity } from "@/interfaces/entity";
import { doesEntityAllow } from "@/utils/permissions";
import { getUser } from "@/utils/users.be";
import { requestUser } from "@/utils/api";
import { isAdmin } from "@/utils/users";

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

	const entity = await (!!showRoles ? getEntityWithRoles : getEntity)(id);
	res.status(200).json(entity);
}

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 entity = await getEntityWithRoles(id)
	if (!entity) return res.status(404).json({ ok: false })

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

	await deleteEntity(entity)
	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 };

	if (!user.entities.map((x) => x.id).includes(id) && !isAdmin(user)) {
		return res.status(403).json({ ok: false });
	}

	if (req.body.label) {
		const entity = await db.collection<Entity>("entities").updateOne({ id }, { $set: { label: req.body.label } });
		return res.status(200).json({ ok: entity.acknowledged });
	}

	if (req.body.licenses) {
		const entity = await db.collection<Entity>("entities").updateOne({ id }, { $set: { licenses: req.body.licenses } });
		return res.status(200).json({ ok: entity.acknowledged });
	}

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