// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, getDoc, doc, deleteDoc, setDoc, getDocs, collection, where, query} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Ticket} from "@/interfaces/ticket";
import {Invite} from "@/interfaces/invite";
import {Group, User} from "@/interfaces/user";
import {v4} from "uuid";
import {sendEmail} from "@/email";

const db = getFirestore(app);

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 snapshot = await getDoc(doc(db, "invites", id));

	if (snapshot.exists()) {
		const invite = {...snapshot.data(), id: snapshot.id} as Invite;
		if (invite.to !== req.session.user.id) return res.status(403).json({ok: false});

		await deleteDoc(snapshot.ref);
		const invitedByRef = await getDoc(doc(db, "users", invite.from));
		if (!invitedByRef.exists()) return res.status(404).json({ok: false});

		const invitedBy = {...invitedByRef.data(), id: invitedByRef.id} as User;

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