const express = require('express');
const router = express.Router();
const db = require('../database/db'); 

// POST route to add a new category
router.post('/add', (req, res) => {
    console.log('Request body:', req.body); 
    const { category } = req.body; 

    if (!category) {
        return res.status(400).json({ error: 'Category is required' });
    }

    const query = 'SELECT * FROM categories WHERE category = ?';
    db.query(query, [category], (err, results) => {
        if (err) {
            console.error('Error checking category:', err);
            return res.status(500).json({ error: 'Server error' });
        }
        if (results.length > 0) {
            return res.status(400).json({ error: 'Category already exists' });
        }

        const insertQuery = 'INSERT INTO categories (category) VALUES (?)';
        db.query(insertQuery, [category.trim()], (err, results) => {
            if (err) {
                console.error('Error adding category:', err);
                return res.status(500).json({ error: 'Server error' });
            }
            res.status(201).json({ id: results.insertId, category: category });
        });
    });
});

// GET route to fetch all categories
router.get('/all', (req, res) => {
    const query = 'SELECT * FROM categories ORDER BY category ASC';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error fetching categories:', err);
            return res.status(500).json({ error: 'Server error' });
        }
        res.status(200).json(results);
    });
});

module.exports = router;
