import type {NextApiRequest, NextApiResponse} from "next";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import { FirebaseScrypt } from 'firebase-scrypt';
import { firebaseAuthScryptParams } from "@/firebase";
import crypto from 'crypto';
import axios from "axios";

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 scrypt = new FirebaseScrypt(firebaseAuthScryptParams)

	const users = req.body.users as {
		email: string;
		name: string;
		type: string;
		passport_id: string;
        groupName?: string;
        corporate?: string;
		studentID?: string;
        expiryDate?: string;
		demographicInformation: {
			country?: string;
			passport_id?: string;
			phone: string;
		};
		passwordHash: string | undefined;
		passwordSalt: string | undefined;
	}[];

	const usersWithPasswordHashes = await Promise.all(users.map(async (user) => {
		const currentUser = { ...user };
		const salt = crypto.randomBytes(16).toString('base64');
		const hash = await scrypt.hash(user.passport_id, salt);
		
		currentUser.email = currentUser.email.toLowerCase();
		currentUser.passwordHash = hash;
		currentUser.passwordSalt = salt;
		return currentUser;
	}));
	
	const backendRequest = await axios.post(`${process.env.BACKEND_URL}/batch_users`, { makerID: maker.id, users: usersWithPasswordHashes }, {
		headers: {
			Authorization: `Bearer ${process.env.BACKEND_JWT}`,
		},
	});

	return res.status(backendRequest.status).json(backendRequest.data)
}
