const adminModel = require("../models/admin");
const bcrypt = require("bcrypt");

const validateAdmin = async (req) => {
    const { email } = req.body;
    const admin = await adminModel.findOne({ email: email });
    return admin
};

const signup = async (req) => {
    const hash = await bcrypt.hash(req.body.password, 10);
    const newAdmin = new adminModel(req.body);
    newAdmin.password = hash;
    const result = await newAdmin.save();
    return result
};

const getAdmin = async (req) => {
    const { adminId } = req.body;
    const admin = await adminModel.findById(adminId);
    return admin
};

const updateAdmin = async (req) => {
    const { adminId } = req.body;
    const updatedData = req.body;

    if(updatedData.newPassword) {
        const hash = await bcrypt.hash(updatedData.newPassword, 10);
        updatedData.password = hash;
    };

    const admin = await adminModel.findByIdAndUpdate(adminId, 
        { $set: updatedData },
        { new: true }
    ).select("-password");
    return admin
};

const deleteAdmin = async (req) => {
    const { adminId } = req.body;
    const admin = await adminModel.findByIdAndDelete(adminId);
    return admin
};

module.exports = {
    validateAdmin,
    signup,
    getAdmin,
    updateAdmin,
    deleteAdmin
};