import {NextApiRequest, NextApiResponse} from "next";
import {getAuth, signInWithEmailAndPassword} from "firebase/auth";
import {app} from "@/firebase";
import {sessionOptions} from "@/lib/session";
import {withIronSessionApiRoute} from "iron-session/next";
import {User} from "@/interfaces/user";
import client from "@/lib/mongodb";

const auth = getAuth(app);

export default withIronSessionApiRoute(login, sessionOptions);

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

	signInWithEmailAndPassword(auth, email.toLowerCase(), password)
		.then(async (userCredentials) => {
			const userId = userCredentials.user.uid;

			const db = client.db(process.env.MONGODB_DB);
			const user = await db.collection("users").findOne<User>({id: userId});

			if (!user) return res.status(401).json({error: 401, message: "User does not exist!"});

			req.session.user = {...user, id: userId};
			await req.session.save();

			res.status(200).json({user: {...user, id: userId}});
		})
		.catch((error) => {
			console.log(error);
			res.status(401).json({error});
		});
}
