// 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 {Type, User} from "@/interfaces/user";
import {PERMISSIONS} from "@/constants/userPermissions";
import {uuidv4} from "@firebase/util";
import {prepareMailer, prepareMailOptions} from "@/email";
import * as Stripe from "stripe";
import ShortUniqueId from "short-unique-id";
import moment from "moment";


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

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
	const {email, days, key, checkout} = req.body as {email: string; days: string; key: string; checkout: string};
	if (!key || key !== process.env.STRIPE_KEY) {
		res.status(403).json({ok: false});
		return;
	}

	const uid = new ShortUniqueId();
	const code = uid.randomUUID(6);

	const codeCheckerRef = await db.collection("codes").find({ checkout: checkout }).toArray();
	if (codeCheckerRef.length !== 0) {
		res.status(401).json({ok: false});
		return;
	}

	const emailCheckerRef = await db.collection("users").find({ email: email }).toArray();
	if (emailCheckerRef.length !== 0) {
		const user = emailCheckerRef[0];
		if (!user.subscriptionExpirationDate) {
			res.status(200).json({ok: true});
			return;
		}

		const codeUserRef = await db.collection("codes").find({ userId: user.id }).toArray();
		const userCode = codeUserRef[0];

		if (userCode.checkout && userCode.checkout === checkout) {
			res.status(401).json({ok: false});
			return;
		}
		await db.collection("users").updateOne(
			{ id: user.id },
			{ $set: {subscriptionExpirationDate: moment(user.subscriptionExpirationDate).add(days, "days").toISOString()} }
		);
		await db.collection("codes").updateOne(
			{ id: userCode.id },
			{ $set: {checkout} }
		  );

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

	await db.collection("codes").updateOne(
		{ id: code },
		{ $set: {type: "student", code, expiryDate: moment(new Date()).add(days, "days").toISOString(), checkout} }
	);

	const transport = prepareMailer();
	const mailOptions = prepareMailOptions(
		{
			type: "student",
			code,
			environment: process.env.ENVIRONMENT,
		},
		[email],
		"EnCoach Registration",
		"main",
	);

	await transport.sendMail(mailOptions);

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