import {NextApiRequest, NextApiResponse} from "next";
import {getAuth} from "firebase-admin/auth";
import {adminApp} from "@/firebase";
import client from "@/lib/mongodb";
import {sessionOptions} from "@/lib/session";
import {withIronSessionApiRoute} from "iron-session/next";

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

const auth = getAuth(adminApp);

export default withIronSessionApiRoute(verify, sessionOptions);

async function verify(req: NextApiRequest, res: NextApiResponse) {
	const {email} = req.body as {email: string};

	const user = await auth.getUserByEmail(email);
	if (!user) {
		res.status(404).json({ok: false});
		return;
	}

	await db.collection("users").updateOne(
		{ id: user.uid},
		{ $set: {isVerified: true} }
	);

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