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

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

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	// due to integration with the homepage the POST request should be public
	if (req.method === "POST") {
		await post(req, res);
		return;
	}

	// specific logic for the preflight request
	if (req.method === "OPTIONS") {
		res.status(200).end();
		return;
	}
	if (!req.session.user) {
		res.status(401).json({ ok: false });
		return;
	}

	if (req.method === "GET") {
		await get(req, res);
	}
}

async function get(req: NextApiRequest, res: NextApiResponse) {
	const docs = await db.collection("tickets").find<Ticket>({}).toArray();

	// fetch all groups for these users
	const reporters = [...new Set(docs.map((d) => d.reporter.id).filter((id) => id))];

	const groups = await db.collection("groups").find<Group>({
		participants: { $in: reporters }
	}).toArray();

	// based on the admin of each group, verify if it exists and it's of type corporate
	const groupsAdmins = [...new Set(groups.map((g) => g.admin).filter((id) => id))];
	const admins = groupsAdmins.length > 0
		? await db.collection("users").find<CorporateUser>({ id: { $in: groupsAdmins }, type: "corporate" }).toArray()
		: [];

	const docsWithAdmins = docs.map((d) => {
		const group = groups.find((g) => g.participants.includes(d.reporter.id));
		const admin = admins.find((a) => a.id === group?.admin);

		if (admin) {
			return {
				...d,
				corporate: admin.corporateInformation?.companyInformation?.name,
			};
		}

		return d;
	}) as TicketWithCorporate[];

	res.status(200).json(docsWithAdmins);
}

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

	const shortUID = new ShortUniqueId();
	const id = body.id || shortUID.randomUUID(8);
	await db.collection("tickets").updateOne(
		{ id: id },
		{ $set: { ...body, id: id } }
	);

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

	try {
		await sendEmail(
			"submittedFeedback",
			{
				id,
				subject: body.subject,
				reporter: body.reporter,
				date: moment(body.date).format("DD/MM/YYYY - HH:mm"),
				type: TicketTypeLabel[body.type],
				reportedFrom: body.reportedFrom,
				description: body.description,
				environment: process.env.ENVIRONMENT,
			},
			[body.reporter.email],
			`Ticket ${id}: ${body.subject}`,
		);
	} catch (e) {
		console.log(e);
	}
}
