const HotSelling = require("../models/HotSelling");

exports.getAllHotSellings = async (req, res) => {
    try {
        const hotSellings = await HotSelling.find();
        res.status(200).json(hotSellings);
    } catch (error) {
        res.status(500).json({ message: 'Failed to fetch hot sellings', error });
    }
};

// Set a specific hot selling item as active
exports.setHotSellingActive = async (req, res) => {
    const { id } = req.params;
    try {
        await HotSelling.updateMany({}, { isActive: false });
        const hotSelling = await HotSelling.findByIdAndUpdate(id, { isActive: true }, { new: true });
        if (!hotSelling) {
            return res.status(404).json({ message: 'Hot selling item not found' });
        }
        res.status(200).json(hotSelling);
    } catch (error) {
        res.status(500).json({ message: 'Failed to set hot selling item as active', error });
    }
};

exports.getHotSellingActive = async (req, res) => {
    try {
        const activeHotSellings = await HotSelling.findOne({ isActive: true });
        res.status(200).json(activeHotSellings);
    } catch (error) {
        res.status(500).json({ message: 'Failed to fetch active hot sellings', error });
    }
};

exports.createHotSelling = async (req, res) => {
    const { title, link, image, description, tagLine, isActive } = req.body;
    const newHotSelling = new HotSelling({
        title,
        link,
        image,
        description,
        tagLine,
        isActive
    });

    try {
        const savedHotSelling = await newHotSelling.save();
        res.status(201).json(savedHotSelling);
    } catch (error) {
        res.status(500).json({ message: 'Failed to create hot selling item', error });
    }
};

exports.updateHotSelling = async (req, res) => {
    const { id } = req.params;
    const updates = req.body;

    try {
        const updatedHotSelling = await HotSelling.findByIdAndUpdate(id, updates, { new: true });
        if (!updatedHotSelling) {
            return res.status(404).json({ message: 'Hot selling item not found' });
        }
        res.status(200).json(updatedHotSelling);
    } catch (error) {
        res.status(500).json({ message: 'Failed to update hot selling item', error });
    }
};

exports.deleteHotSelling = async (req, res) => {
    const { id } = req.params;

    try {
        const deletedHotSelling = await HotSelling.findByIdAndDelete(id);
        if (!deletedHotSelling) {
            return res.status(404).json({ message: 'Hot selling item not found' });
        }
        res.status(200).json({ message: 'Hot selling item deleted' });
    } catch (error) {
        res.status(500).json({ message: 'Failed to delete hot selling item', error });
    }
};
