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

const db = getFirestore(app);

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") await get(req, res);
	if (req.method === "POST") await post(req, res);
}

async function get(req: NextApiRequest, res: NextApiResponse) {
	const snapshot = await getDocs(collection(db, "invites"));

	res.status(200).json(
		snapshot.docs.map((doc) => ({
			id: doc.id,
			...doc.data(),
		})),
	);
}

async function post(req: NextApiRequest, res: NextApiResponse) {
	const body = req.body as Invite;

	const existingInvites = (await getDocs(collection(db, "invites"))).docs.map((x) => ({...x.data(), id: x.id})) as Invite[];

	const invitedRef = await getDoc(doc(db, "users", body.to));
	if (!invitedRef.exists()) return res.status(404).json({ok: false});

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

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

	try {
		await sendEmail(
			"receivedInvite",
			{
				name: invited.name,
				corporateName:
					invitedBy.type === "corporate" ? invitedBy.corporateInformation?.companyInformation?.name || invitedBy.name : invitedBy.name,
				environment: process.env.ENVIRONMENT,
			},
			[invited.email],
			"You have been invited to a group!",
		);
	} catch (e) {
		console.log(e);
	}

	if (existingInvites.filter((i) => i.to === body.to && i.from === body.from).length == 0) {
		const shortUID = new ShortUniqueId();
		await setDoc(doc(db, "invites", body.id || shortUID.randomUUID(8)), body);
	}

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