const Tradenewarival = require("../models/Tradenewarrival");


exports.addNewUpdate = async (req, res) => {
    try {
        const { Data } = req.body; // Destructure DataNumber and Data from req.body 
        console.log("Abc-------", Data);
        let existingData = await Tradenewarival.findOne({});
        if (existingData) {
            if (Data.DataNumber === 1) {
                await Tradenewarival.updateOne({}, { One: Data });
            } else if (Data.DataNumber === 2) {
                await Tradenewarival.updateOne({}, { Two: Data });
            } else if (Data.DataNumber === 3) {
                await Tradenewarival.updateOne({}, { Three: Data });
            } else if (Data.DataNumber === 4) {
                await Tradenewarival.updateOne({}, { Four: Data });
            }
        } else {
            // No data exists, create a new entry with all fields set to empty arrays
            if (Data.DataNumber === 1) {
                newarival = new Tradenewarival({ One: Data });
            } else if (Data.DataNumber === 2) {
                newarival = new Tradenewarival({ Two: Data });
            } else if (Data.DataNumber === 3) {
                newarival = new Tradenewarival({ Three: Data });
            } else if (Data.DataNumber === 4) {
                newarival = new Tradenewarival({ Four: Data });
            }

            try {
                await newarival.save();
                console.log('Data saved successfully:', newarival);
            } catch (saveError) {
                console.error('Error saving data:', saveError);
                throw saveError; // Rethrow the error to be caught by the outer catch block
            }
        }

        res.status(200).json({ message: "success" });
    } catch (error) {
        res.status(500).json({ message: "Error in adding Variant", error: error.message });
    }
};







exports.getAll = async (req, res) => {
    try { 
        let data = await Tradenewarival.find({}); 
        res.status(200).json({ message: "success", data });
    } catch (error) {
        res.status(500).json({ message: "Error in adding Variant", error: error.message });
    }
};

