// 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 {User} from "@/interfaces/user";
import {sendEmail} from "@/email";

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

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

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