// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, setDoc, doc, getDocs, query, collection, where} from "firebase/firestore";
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 = getFirestore(app);

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 getDocs(query(collection(db, "codes"), where("checkout", "==", checkout)));
	if (codeCheckerRef.docs.length !== 0) {
		res.status(401).json({ok: false});
		return;
	}

	const emailCheckerRef = await getDocs(query(collection(db, "users"), where("email", "==", email)));
	if (emailCheckerRef.docs.length !== 0) {
		const user = emailCheckerRef.docs[0];
		if (!user.data().subscriptionExpirationDate) {
			res.status(200).json({ok: true});
			return;
		}

		const codeUserRef = await getDocs(query(collection(db, "codes"), where("userId", "==", user.id)));
		const userCode = codeUserRef.docs[0];

		if (userCode.data().checkout && userCode.data().checkout === checkout) {
			res.status(401).json({ok: false});
			return;
		}

		await setDoc(
			user.ref,
			{subscriptionExpirationDate: moment(user.data().subscriptionExpirationDate).add(days, "days").toISOString()},
			{merge: true},
		);
		await setDoc(userCode.ref, {checkout}, {merge: true});

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

	const codeRef = doc(db, "codes", code);
	await setDoc(codeRef, {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});
}
