// 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 {getAssignmentsByAssigner, getAssignmentsForCorporates} 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 await GET(req, res);

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

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

	const startDateParsed = startDate ? new Date(startDate) : undefined;
	const endDateParsed = endDate ? new Date(endDate) : undefined;
	try {
		const idsList = ids.split(",");

		const assignments = await getAssignmentsForCorporates(req.session.user!.type, idsList, startDateParsed, endDateParsed);
		res.status(200).json(assignments);
	} catch (err: any) {
		res.status(500).json({error: err.message});
	}
}
