// 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 } from "@/utils/entities.be";
import { Entity, WithEntities, WithEntity, WithLabeledEntities } from "@/interfaces/entity";
import { v4 } from "uuid";
import { mapBy } from "@/utils";
import { getEntitiesUsers, getUser, getUsers } from "@/utils/users.be";
import { Group, User } from "@/interfaces/user";
import { getGroups, getGroupsByEntities } from "@/utils/groups.be";
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);
}

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

  const groups: WithEntity<Group>[] = ["admin", "developer"].includes(user.type)
    ? await getGroups()
    : await getGroupsByEntities(mapBy(user.entities || [], 'id'))

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