const AcademyCategoryModel = require('../../../models/AcademyCategoryModel');
// GET all categories
exports.getAll = async (req, res) => {
    try {
        const categories = await AcademyCategoryModel.find({}).sort({ createdAt: -1 });
        res.status(200).json({ success: true, categories });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
};

// CREATE category
exports.create = async (req, res) => {
    try {
        const { title, status } = req.body;

        if (!title) {
            return res.status(400).json({ success: false, message: "title is required" });
        }

        const newCategory = new AcademyCategoryModel({
            title,
            status: status ?? true,
        });

        await newCategory.save();

        res.status(201).json({ success: true, category: newCategory });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
};

// UPDATE category
exports.update = async (req, res) => {
    try {
        const { id } = req.params;
        const { title, status } = req.body;

        const updated = await AcademyCategoryModel.findByIdAndUpdate(
            id,
            { title, status },
            { new: true, runValidators: true }
        );

        if (!updated) {
            return res.status(404).json({ success: false, message: "category not found" });
        }

        res.status(200).json({ success: true, category: updated });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
};

// DELETE
exports.remove = async (req, res) => {
    try {
        const { id } = req.params;

        const deleted = await AcademyCategoryModel.findByIdAndDelete(id);

        if (!deleted) {
            return res.status(404).json({ success: false, message: "category not found" });
        }

        res.status(200).json({
            success: true,
            message: 'category deleted successfully'
        });
    } catch (error) {
        res.status(500).json({ success: false, message: error.message });
    }
};
