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

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

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

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

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

// Fetch all levels
router.get('/all', (req, res) => {
    const query = 'SELECT * FROM levels';
    db.query(query, (err, results) => {
        if (err) {
            console.error('Error fetching levels:', err);
            return res.status(500).json({ error: 'Server error' });
        }
        res.status(200).json(results);
    });
});

module.exports = router;
