import {NextApiRequest, NextApiResponse} from "next";
import {getAuth} from "firebase-admin/auth";
import {adminApp, app} from "@/firebase";
import {sessionOptions} from "@/lib/session";
import {withIronSessionApiRoute} from "iron-session/next";
import {doc, getFirestore, setDoc} from "firebase/firestore";

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

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;
	}

	const userRef = doc(db, "users", user.uid);
	await setDoc(userRef, {isVerified: true}, {merge: true});

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