import { apiHandler, db } from "@/helpers/api";
import bcrypt from 'bcryptjs';

export default apiHandler({
	post: updateUserData,
});

async function updateUserData(req, res) {
	const userID = req.userID;
	const formData = req.body;

	if (!db.initialized) await db.initialize();

	try {
		const userData = await db.User.findByPk(userID);

		if (!userData) {
			return res.status(404).json({ success: false, error: "Utilizator necunoscut!" });
		}

		if (userData.id != userID) {
			return res.status(401).json({ success: false, error: "Neautorizat!" });
		}

		userData.firstName = formData.firstName || userData.firstName;
		userData.lastName = formData.lastName || userData.lastName;
		userData.email = formData.email || userData.email;

		if (formData.currentPassword && formData.newPassword && formData.passwordConfirm) {
			if (formData.newPassword !== formData.passwordConfirm) {
				return res.status(200).json({ success: false, error: "Parolele nu corespund!" });
			}

               const email = userData.email; 
               const user = await db.User.scope('withHash').findOne({ where: { email } });
			const isMatch = await bcrypt.compareSync(formData.currentPassword, user.hash);
			if (!isMatch) {
				return res.status(200).json({ success: false, error: "Parola curentă este incorectă!" });
			}

			userData.password = formData.newPassword;
		}

		await userData.save();

		return res.status(200).json({ success: true });
	} catch (error) {
		console.error(error);
		return res.status(500).json({ success: false, error: "Eroare la prelucrarea datelor utilizatorului." });
	}
}
