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

const db = client.db(process.env.MONGODB_DB);

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 db.collection("invites").find({}).toArray();
	res.status(200).json(snapshot);
}

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

	const existingInvites = await db.collection("invites").find<Invite>({}).toArray();

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

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

	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 db.collection("invites").updateOne(
			{ id: body.id || shortUID.randomUUID(8)},
			{ $set: body },
			{ upsert: true}
		);
	}

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