import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, setDoc, doc, query, collection, where, getDocs, getDoc, deleteDoc, limit, updateDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {v4} from "uuid";
import {Group} from "@/interfaces/user";
import {createUserWithEmailAndPassword, getAuth} from "firebase/auth";

const DEFAULT_DESIRED_LEVELS = {
	reading: 9,
	listening: 9,
	writing: 9,
	speaking: 9,
};

const DEFAULT_LEVELS = {
	reading: 0,
	listening: 0,
	writing: 0,
	speaking: 0,
};

const auth = getAuth(app);
const db = getFirestore(app);

export default withIronSessionApiRoute(handler, sessionOptions);

async function handler(req: NextApiRequest, res: NextApiResponse) {
	if (req.method === "POST") return post(req, res);

	return res.status(404).json({ok: false});
}

async function post(req: NextApiRequest, res: NextApiResponse) {
	const maker = req.session.user;
	if (!maker) {
		return res.status(401).json({ok: false, reason: "You must be logged in to make user!"});
	}
	const {email, passport_id, type, groupName, expiryDate} = req.body as {
		email: string;
		passport_id: string;
		type: string;
		groupName: string;
		expiryDate: null | Date;
	};
	// cleaning data
	delete req.body.passport_id;
	delete req.body.groupName;
	delete req.body.expiryDate;

	await createUserWithEmailAndPassword(auth, email.toLowerCase(), passport_id)
		.then(async (userCredentials) => {
			const userId = userCredentials.user.uid;

			const user = {
				...req.body,
				bio: "",
				type: type,
				focus: "academic",
				status: "active",
				desiredLevels: DEFAULT_DESIRED_LEVELS,
				levels: DEFAULT_LEVELS,
				isFirstLogin: false,
				isVerified: true,
				registrationDate: new Date(),
				subscriptionExpirationDate: expiryDate || null,
			};
			await setDoc(doc(db, "users", userId), user);
			if (type === "corporate") {
				const defaultTeachersGroup: Group = {
					admin: userId,
					id: v4(),
					name: "Teachers",
					participants: [],
					disableEditing: true,
				};

				const defaultStudentsGroup: Group = {
					admin: userId,
					id: v4(),
					name: "Students",
					participants: [],
					disableEditing: true,
				};

				const defaultCorporateGroup: Group = {
					admin: userId,
					id: v4(),
					name: "Corporate",
					participants: [],
					disableEditing: true,
				};

				await setDoc(doc(db, "groups", defaultTeachersGroup.id), defaultTeachersGroup);
				await setDoc(doc(db, "groups", defaultStudentsGroup.id), defaultStudentsGroup);
				await setDoc(doc(db, "groups", defaultCorporateGroup.id), defaultCorporateGroup);
			}

			if (typeof groupName === "string" && groupName.trim().length > 0) {
				const q = query(collection(db, "groups"), where("admin", "==", maker.id), where("name", "==", groupName.trim()), limit(1));
				const snapshot = await getDocs(q);

				if (snapshot.empty) {
					const values = {
						id: v4(),
						admin: maker.id,
						name: groupName.trim(),
						participants: [userId],
						disableEditing: false,
					};

					await setDoc(doc(db, "groups", values.id), values);
				} else {
					const doc = snapshot.docs[0];
					const participants: string[] = doc.get("participants");

					if (!participants.includes(userId)) {
						updateDoc(doc.ref, {
							participants: [...participants, userId],
						});
					}
				}
			}

			console.log(`Returning - ${email}`);
			return res.status(200).json({ok: true});
		})
		.catch((error) => {
			console.log(`Failing - ${email}`);
			console.log(error);
			return res.status(401).json({error});
		});
}
