// 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 {Payment} from "@/interfaces/paypal";
import {PaymentsStatus} from "@/interfaces/user.payments";
import client from "@/lib/mongodb";

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);

	res.status(404).json(undefined);
}

// user can fetch payments assigned to him as an agent
async function get(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ok: false});
		return;
	}

	const payments = await db
		.collection("payments")
		.find(["admin", "developer"].includes(req.session.user.type) ? {} : {[req.session.user.type]: req.session.user.id})
		.toArray();

	if (payments.length === 0) {
		res.status(200).json({
			pending: [],
			done: [],
		});
		return;
	}

	const paidStatusEntries = payments.reduce(
		(acc: PaymentsStatus, doc) => {
			if (doc.isPaid) {
				return {
					...acc,
					done: [...acc.done, doc.corporate],
				};
			}

			return {
				...acc,
				pending: [...acc.pending, doc.corporate],
			};
		},
		{
			pending: [],
			done: [],
		},
	);
	res.status(200).json({
		pending: [...new Set(paidStatusEntries.pending)],
		done: [...new Set(paidStatusEntries.done)],
	});
}
