import User from "../models/UserModels.js";

//create
export const userCreate = async (req,res) => {
    try{
        const user = await User.create(req.body);
        res.status(201).json(user);
    }catch(error){
        res.status(500).json({message:error.message});
    }
};

//read

export const getUser = async (req,res) => {
    try{
        const user = await User.find();
        res.status(200).json(user);
    }catch(error){
        res.status(500).json({message:error.message});
    }
};

//update

export const updateUser = async (req,res) => {
    try{
        const user = await User.findByIdAndUpdate(req.params.id, req.body, {new:true});
        res.status(200).json(user);
    }catch(error){
res.status(500).json({message:error.message});
    }
};

//delete

export const deleteUser = async (req,res) => {
    try{
        const user = await User.findByIdAndDelete(req.params.id);
        res.status(200).json({message:"user deleted"});
    }catch(error){
        res.status(500).json({message:error.message});
    }
};
 
export const registerUser = async (req,res) => {
    try{
        const user = await User.create(req.body);
        res.status(201).json({ message:"user registerd successfully", user, });
    }catch(error){
        res.status(500).json({message:error.message});
    }
};

export const loginUser = async (req,res) => {
    try{
        const {userName, password} = req.body;
        const user = await User.findOne({userName});

        if(!user) {
            return res.status(400).json({message:"user not found"});
        }
        if (user.password !== password){
            return res.status(400).json({message:"wrong password"});
        }
        res.json({message:"Login successfully", user,
        });
}catch(error){
    res.status(500).json({message:error.message});
}
};