const Subscriber  = require('./../models/Subscriber.js');

exports.AddSubscriber = async function(req,res){
    try{
        const {email} = req.body;
        if(!email){
            return res.status(404).json({success:false,message:"Email was required"});
        }
        const oldsub = await Subscriber.findOne({email});
        if(oldsub){
            return res.status(409).json({success:false,message:"Already Subscribed"});
        }
        const sub = await Subscriber.create({email});
        if(!sub){
            return res.status(423).json({success:false,message:"Unable to create Subscriber"});
        }
        return res.status(200).json({success:true,message:"User Subscriber Successfully"});
    }catch(error){
        res.status(500).json({success:false,message:error.message});
    }
}

exports.GetAllSubscribers = async function(req,res){
    try{
        const subscribers = await Subscriber.find({});
        return res.status(200).json({success:true,message:"Subscribers Found Successfully",subscribers});
    }catch(error){
        res.status(500).json({success:false,message:error.message});
    }
}

exports.DeleteSubscriber = async function(req,res){
    try{
        const id = req.params.id;
        if(!id){
            return res.status(404).json({success:false,message:"Unable to get the id of subscriber"});
        }
        await Subscriber.findByIdAndDelete(id);
        res.status(200).json({ success: true, message: "Subscriber deleted successfully" });
    }catch(err){
        return res.status(500).json({success:false,message:error.message});
    }
}

