// 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 {getLinkedUsers} from "@/utils/users.be";
import {Type} from "@/interfaces/user";
import {uniqBy} from "lodash";

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user && !req.headers["page"] && req.headers["page"] !== "register") {
		res.status(401).json({ok: false});
		return;
	}

	const {
		size,
		type,
		page,
		orderBy,
		direction = "desc",
	} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"};

	const {users, total} = await getLinkedUsers(
		req.session.user?.id,
		req.session.user?.type,
		type,
		page !== undefined ? parseInt(page) : undefined,
		size !== undefined ? parseInt(size) : undefined,
		orderBy,
		direction,
	);

	res.status(200).json({users: uniqBy([...users], "id"), total});
}
