import RetailDistributor from "./RetailDistributorModel.js";
import validator from "validator";
import password from "secure-random-password";
import crypto from "crypto";
import sendEmail, { sendOtp } from "../../Utils/sendEmail.js";
export const loginRD = async (req, res) => {
const { email, password } = req.body;
try {
if (!email || !password) {
return res.status(400).json({ message: "Please Enter Email & Password" });
}
const retailDistributor = await RetailDistributor.findOne({ email }).select(
"+password"
);
if (!retailDistributor) {
return res.status(400).json({ message: "Invalid Email or Password" });
}
const isPasswordMatched = await retailDistributor.comparePassword(password);
if (!isPasswordMatched) {
return res.status(400).json({ message: "Invalid Email or Password" });
}
const token = retailDistributor.getJWTToken();
return res.status(200).json({
success: true,
token,
message: "Login Successfully",
});
} catch (error) {
return res.status(500).json({
message: error.message ? error.message : "Something went wrong!",
});
}
};
export const ChangePasswordRD = async (req, res) => {
// Retrieve id from req.params
const { oldPassword, newPassword, confirmPassword } = req.body;
const userId = req.user._id; // Use the ID from the URL or from the authenticated user
// console.log(userId);
if (!oldPassword) {
return res.status(400).json({ message: "Please Enter Old password" });
}
if (!newPassword) {
return res.status(400).json({ message: "Please Enter New Password " });
}
if (!confirmPassword) {
return res.status(400).json({ message: "Please Enter Confirm Password" });
}
try {
const retailDistributor = await RetailDistributor.findById(userId).select(
"+password"
);
if (!retailDistributor) {
return res.status(404).json({ message: "Retail Distributer not found" });
}
const isPasswordMatched = await retailDistributor.comparePassword(
oldPassword
);
if (!isPasswordMatched) {
return res.status(400).json({ message: "Old password is incorrect" });
}
if (newPassword !== confirmPassword) {
return res
.status(400)
.json({ message: "New password and confirm Password do not match" });
}
retailDistributor.password = newPassword;
await retailDistributor.save();
return res
.status(200)
.json({ success: true, message: "Password updated successfully" });
} catch (error) {
console.error("Error updating password:", error);
return res.status(500).json({
message: error.message ? error.message : "Server error!",
});
}
};
export const forgotPasswordRD = async (req, res) => {
try {
// Check if email is provided
const { email } = req.body;
if (!email) {
return res.status(400).json({ message: "Please Enter Email!" });
}
// Find the Retail Distributor by email
const retailDistributor = await RetailDistributor.findOne({ email });
if (!retailDistributor) {
return res.status(404).json({ message: "Retail Distributor not found" });
}
// Generate a random password
const newPassword = password.randomPassword({
length: 12,
characters: [
{ characters: password.upper, exactly: 1 }, // At least 1 uppercase letter
{ characters: password.symbols, exactly: 1 }, // At least 1 symbol
password.lower, // Lowercase letters
password.digits, // Digits
],
});
// Update the retail distributor's password
retailDistributor.password = newPassword;
await retailDistributor.save(); // The pre-save hook in your schema will handle password hashing
// Send an email to the retail distributor with the new password
await sendEmail({
to: retailDistributor.email,
from: process.env.SEND_EMAIL_FROM,
subject: `Cheminova Password Recovery`,
html: `Your new password is: ${newPassword}
If you did not request this, please ignore this email.`,
});
// Respond with success message
return res.status(200).json({
success: true,
message: `Email sent to ${retailDistributor.email} successfully`,
});
} catch (error) {
console.error("Error during password reset:", error);
return res.status(500).json({
message: error.message || "Something went wrong!",
});
}
};
export const UpdateProfileRD = async (req, res) => {
const { name, mobile_number } = req.body; // Only expecting name from the request body
const userId = req.user._id; // User ID from authenticated user
try {
// Find the RetailDistributor by user ID
const retailDistributor = await RetailDistributor.findById(userId);
if (!retailDistributor) {
return res.status(404).json({ message: "Retail Distributor not found" });
}
// Assuming you have an 'isVerified' field in your RetailDistributor schema
// Update name if provided
if (name) {
retailDistributor.name = name;
retailDistributor.mobile_number = mobile_number
? mobile_number
: retailDistributor.mobile_number;
} else {
return res.status(400).json({ message: "Name is required" });
}
// Save the updated RetailDistributor
await retailDistributor.save();
return res.status(200).json({
retailDistributor,
message: "Profile updated successfully",
});
} catch (error) {
return res.status(500).json({
message: error.message || "Server error!",
});
}
};
export const getmyProfileRD = async (req, res) => {
try {
// Fetch the profile data using the authenticated user's ID
const myData = await RetailDistributor.findById(req.user?._id);
if (myData) {
return res.status(200).json({
success: true,
message: "Profile fetched successfully!",
myData,
});
} else {
return res.status(404).json({
success: false,
message: "Retail Distributor not found",
});
}
} catch (error) {
return res.status(500).json({
success: false,
message: error.message || "Something went wrong!",
});
}
};