// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import client from "@/lib/mongodb";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Invite } from "@/interfaces/invite";
import { CorporateUser, Group, User } from "@/interfaces/user";
import { v4 } from "uuid";
import { sendEmail } from "@/email";
import { updateExpiryDateOnGroup } from "@/utils/groups.be";

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

async function addToInviterGroup(user: User, invitedBy: User) {
	const invitedByGroups = await db.collection("groups").find<Group>({ admin: invitedBy.id }).toArray();
	const typeGroupName = user.type === "student" ? "Students" : user.type === "teacher" ? "Teachers" : undefined;

	if (typeGroupName) {
		const typeGroup: Group = invitedByGroups.find((g) => g.name === typeGroupName) || {
			id: v4(),
			admin: invitedBy.id,
			name: typeGroupName,
			participants: [],
			disableEditing: true,
		};

		await db.collection("groups").updateOne(
			{ id: typeGroup.id },
			{
				$set: {
					...typeGroup,
					participants: [...typeGroup.participants.filter((x) => x !== user.id), user.id],
				},
			},
			{ upsert: true }
		);

	}

	const invitationsGroup: Group = invitedByGroups.find((g) => g.name === "Invited") || {
		id: v4(),
		admin: invitedBy.id,
		name: "Invited",
		participants: [],
		disableEditing: true,
	};

	await db.collection("groups").updateOne(
		{ id: invitationsGroup.id },
		{
			$set: {
				...invitationsGroup,
				participants: [...invitationsGroup.participants.filter((x) => x !== user.id), user.id],
			}
		},
		{ upsert: true }
	);
}

async function deleteFromPreviousCorporateGroups(user: User, invitedBy: User) {
	const corporatesRef = await db.collection("users").find<CorporateUser>({ type: "corporate" }).toArray();
	const corporates = corporatesRef.filter((x) => x.id !== invitedBy.id);

	const userGroups = await db.collection("groups").find<Group>({
		participants: user.id
	}).toArray();

	const corporateGroups = userGroups.filter((x) => corporates.map((c) => c.id).includes(x.admin));
	await Promise.all(
		corporateGroups.map(async (group) => {
			await db.collection("groups").updateOne(
				{ id: group.id },
				{ $set: { participants: group.participants.filter((x) => x !== user.id) } },
				{ upsert: true }
			);
		}),
	);
}

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

	const { id } = req.query as { id: string };
	const invite = await db.collection("invites").findOne<Invite>({ id: id});

	if (invite) {
		if (invite.to !== req.session.user.id) return res.status(403).json({ ok: false });

		await db.collection("invites").deleteOne({ id: id });

		const invitedBy = await db.collection("users").findOne<User>({ id: invite.from});
		if (!invitedBy) return res.status(404).json({ ok: false });

		await updateExpiryDateOnGroup(invite.to, invite.from);

		if (invitedBy.type === "corporate") await deleteFromPreviousCorporateGroups(req.session.user, invitedBy);
		await addToInviterGroup(req.session.user, invitedBy);

		try {
			await sendEmail(
				"respondedInvite",
				{
					corporateName: invitedBy.name,
					name: req.session.user.name,
					decision: "accept",
					environment: process.env.ENVIRONMENT,
				},
				[invitedBy.email],
				`${req.session.user.name} has accepted your invite!`,
			);
		} catch (e) {
			console.log(e);
		}

		res.status(200).json({ ok: true });
	} else {
		res.status(404).json(undefined);
	}
}
