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

// POST - Create a new table
router.post('/', async (req, res) => {
    try {
        const table = new Table(req.body);
        await table.save();
        res.send('Table registered');
    } catch (error) {
        res.status(500).send('An error occurred while registering the table');
    }
});

// GET - Retrieve all tables
router.get('/', async (req, res) => {
    try {
        const tables = await Table.find({}).sort('No');
        res.send(tables);
    } catch (error) {
        res.status(500).send('An error occurred while fetching tables');
    }
});

// DELETE - Delete a table by ID
router.delete('/:id', async (req, res) => {
    try {
        const table = await Table.findByIdAndRemove(req.params.id);
        if (!table) return res.status(404).send('Table not found');
        res.send('Table deleted successfully');
    } catch (error) {
        res.status(500).send('An error occurred while deleting the table');
    }
});

// PUT - Update a table by ID
router.put('/:id', async (req, res) => {
    try {
        const table = await Table.findByIdAndUpdate(req.params.id, req.body, {
            new: true, // Returns the updated document
            runValidators: true, // Ensures the new data adheres to the schema
        });
        if (!table) return res.status(404).send('Table not found');
        res.send('Table updated successfully');
    } catch (error) {
        res.status(500).send('An error occurred while updating the table');
    }
});

module.exports = router;
