const Model = require("../models/Models");

exports.getAllModels = async (req, res) => {
    try {
        const models = await Model.find();
        res.status(200).json(models);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.getModelById = async (req, res) => {
    try {
        const model = await Model.findById(req.params.id);
        if (!model) {
        return res.status(404).json({ message: 'Model not found' });
        }
        res.status(200).json(model);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.createModel = async (req, res) => {
    const { title, description, link, image, isMain } = req.body;
    console.log(req.body);
    const newModel = new Model({ title, description, link, image, isMain });

    try {
        const savedModel = await newModel.save();
        res.status(201).json(savedModel);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};

exports.updateModel = async (req, res) => {
    try {
        const updatedModel = await Model.findByIdAndUpdate(req.params.id, req.body, { new: true });
        if (!updatedModel) {
        return res.status(404).json({ message: 'Model not found' });
        }
        res.status(200).json(updatedModel);
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};

exports.deleteModel = async (req, res) => {
    try {
        const deletedModel = await Model.findByIdAndDelete(req.params.id);
        if (!deletedModel) {
            return res.status(404).json({ message: 'Model not found' });
        }
        res.status(200).json({ message: 'Model deleted successfully' });
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

exports.setMainModel = async (req, res) => {
    try {
        await Model.updateMany({ isMain: true }, { $set: { isMain: false } });

        const mainModel = await Model.findByIdAndUpdate(req.params.id, { isMain: true }, { new: true });
        if (!mainModel) {
            return res.status(404).json({ message: 'Model not found' });
        }
        res.status(200).json(mainModel);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};




