// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app, storage} from "@/firebase";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Group, User} from "@/interfaces/user";
import {getDownloadURL, getStorage, ref, uploadBytes} from "firebase/storage";
import {getAuth, signInWithEmailAndPassword, updateEmail, updatePassword} from "firebase/auth";
import {errorMessages} from "@/constants/errors";
import moment from "moment";
import ShortUniqueId from "short-unique-id";
import {Payment} from "@/interfaces/paypal";
import {toFixedNumber} from "@/utils/number";
import {propagateExpiryDateChanges, propagateStatusChange} from "@/utils/propagate.user.changes";
import client from "@/lib/mongodb";

const db = client.db(process.env.MONGODB_DB);
const auth = getAuth(app);

export default withIronSessionApiRoute(handler, sessionOptions);

// TODO: Data is set as any as data cannot be parsed to Payment
// because the id is not a par of the hash and payment expects date to be of type Date
// but if it is not inserted as a string, some UI components will not work (Invalid Date)
const addPaymentRecord = async (data: any) => {
	await db.collection("payments").insertOne(data);
};
const managePaymentRecords = async (user: User, userId: string | undefined): Promise<boolean> => {
	try {
		if (user.type === "corporate" && userId) {
			const shortUID = new ShortUniqueId();
			const data: Payment = {
				id: shortUID.randomUUID(8),
				corporate: userId,
				agent: user.corporateInformation.referralAgent,
				agentCommission: user.corporateInformation.payment!.commission,
				agentValue: toFixedNumber((user.corporateInformation.payment!.commission / 100) * user.corporateInformation.payment!.value, 2),
				currency: user.corporateInformation.payment!.currency,
				value: user.corporateInformation.payment!.value,
				isPaid: false,
				date: new Date().toISOString(),
			};

			const corporatePayments = await db.collection("payments").find({corporate: userId}).toArray();
			if (corporatePayments.length === 0) {
				await addPaymentRecord(data);
				return true;
			}

			const hasPaymentPaidAndExpiring = corporatePayments.filter((doc) => {
				return (
					doc.isPaid &&
					moment().isAfter(moment(user.subscriptionExpirationDate).subtract(30, "days")) &&
					moment().isBefore(moment(user.subscriptionExpirationDate))
				);
			});

			if (hasPaymentPaidAndExpiring.length > 0) {
				await addPaymentRecord(data);
				return true;
			}
		}

		return false;
	} catch (e) {
		// if this process fails it should not stop the rest of the process
		console.log(e);
		return false;
	}
};

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (!req.session.user) {
		res.status(401).json({ok: false});
		return;
	}

	const queryId = req.query.id as string;

	let user = await db.collection("users").findOne<User>({id: queryId ? (queryId as string) : req.session.user.id});
	const updatedUser = req.body as User & {password?: string; newPassword?: string};
	delete (updatedUser as any)._id

	if (!!queryId) {
		await db.collection("users").updateOne({id: queryId}, {$set: updatedUser});

		await managePaymentRecords(updatedUser, updatedUser.id);
		if (updatedUser.status || updatedUser.type === "corporate") {
			// there's no await as this does not affect the user
			propagateStatusChange(queryId, updatedUser.status);
			propagateExpiryDateChanges(queryId, user?.subscriptionExpirationDate, updatedUser.subscriptionExpirationDate || null);
		}

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

	if (updatedUser.profilePicture && updatedUser.profilePicture !== req.session.user.profilePicture) {
		const profilePictureFiletype = updatedUser.profilePicture.split(";")[0].split("/")[1];
		const profilePictureRef = ref(storage, `profile_pictures/${req.session.user.id}.${profilePictureFiletype}`);

		const pictureBytes = Buffer.from(updatedUser.profilePicture.split(";base64,")[1], "base64url");
		const pictureSnapshot = await uploadBytes(profilePictureRef, pictureBytes);

		const pictureReference = ref(storage, pictureSnapshot.metadata.fullPath);
		updatedUser.profilePicture = await getDownloadURL(pictureReference);
	}

	if (updatedUser.newPassword && updatedUser.password) {
		try {
			const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
			await updatePassword(credential.user, updatedUser.newPassword);
		} catch {
			res.status(400).json({error: "E001", message: errorMessages.E001});
			return;
		}
	}

	if (updatedUser.email !== req.session.user.email && updatedUser.password) {
		try {
			const usersWithSameEmail = await db.collection("users").find({email: updatedUser.email.toLowerCase()}).toArray();

			if (usersWithSameEmail.length > 0) {
				res.status(400).json({error: "E003", message: errorMessages.E003});
				return;
			}

			const credential = await signInWithEmailAndPassword(auth, req.session.user.email, updatedUser.password);
			await updateEmail(credential.user, updatedUser.email);

			if (req.session.user.type === "student") {
				const corporateAdmins = (await db.collection("users").find<User>({type: "corporate"}).toArray()).map((x) => x.id);

				const groups = await db
					.collection("groups")
					.find<Group>({
						participants: req.session.user!.id,
						admin: {$in: corporateAdmins},
					})
					.toArray();

				groups.forEach(async (group) => {
					await db
						.collection("groups")
						.updateOne({id: group.id}, {$set: {participants: group.participants.filter((x) => x !== req.session.user!.id)}});
				});
			}
		} catch {
			res.status(400).json({error: "E002", message: errorMessages.E002});
			return;
		}
	}

	if (updatedUser.status) {
		// there's no await as this does not affect the user
		propagateStatusChange(req.session.user.id, updatedUser.status);
	}

	delete updatedUser.password;
	delete updatedUser.newPassword;

	await db.collection("users").updateOne({id: queryId ? (queryId as string) : req.session.user.id}, {$set: updatedUser});

	if (!queryId) {
		req.session.user = updatedUser ? {...updatedUser, id: req.session.user.id} : null;
		await req.session.save();
	}

	if ({...updatedUser, id: req.session.user!.id}) {
		await managePaymentRecords({...updatedUser, id: req.session.user!.id}, queryId);
	}

	res.status(200).json({user: {...updatedUser, ...user, id: req.session.user!.id}});
}

export const config = {
	api: {
		bodyParser: {
			sizeLimit: "20mb",
		},
	},
};
