// 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 {uniqBy} from "lodash";
import {getAllAssignersByCorporate} from "@/utils/groups.be";
import {getAssignmentsByAssigners} from "@/utils/assignments.be";

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ok: false});
		return;
	}

	if (req.method === "GET") return GET(req, res);

	res.status(404).json({ok: false});
}

async function GET(req: NextApiRequest, res: NextApiResponse) {
	const {id} = req.query as {id: string};

	const assigners = await getAllAssignersByCorporate(id, req.session.user!.type);
	const assignments = await getAssignmentsByAssigners([...assigners, id]);

	res.status(200).json(uniqBy(assignments, "id"));
}
