const express = require('express');
const Category = require('../models/Category'); // Make sure to update the path if necessary
const router = express.Router();

// Create a new category
router.post('/', async (req, res) => {
    try {
        const category = new Category(req.body);
        await category.save();
        res.status(201).send('Category registered');
    } catch (error) {
        res.status(400).send(error.message);
    }
});

// Read all categories
router.get('/', async (req, res) => {
    try {
        const categories = await Category.find();
        res.status(200).json(categories);
    } catch (error) {
        res.status(500).send(error.message);
    }
});

// Read a single category by ID
router.get('/:id', async (req, res) => {
    try {
        const category = await Category.findById(req.params.id);
        if (!category) {
            return res.status(404).send('Category not found');
        }
        res.status(200).json(category);
    } catch (error) {
        res.status(500).send(error.message);
    }
});

// Update a category by ID
router.put('/:id', async (req, res) => {
    try {
        const category = await Category.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
        if (!category) {
            return res.status(404).send('Category not found');
        }
        res.status(200).send('Category updated');
    } catch (error) {
        res.status(400).send(error.message);
    }
});

// Delete a category by ID
router.delete('/:id', async (req, res) => {
    try {
        const category = await Category.findByIdAndDelete(req.params.id);
        if (!category) {
            return res.status(404).send('Category not found');
        }
        res.status(200).send('Category deleted');
    } catch (error) {
        res.status(500).send(error.message);
    }
});

module.exports = router;
