const express = require('express');
const router = express.Router();

// Importă conexiunea la baza de date
const pool = require('../db'); 

// GET /users
router.get('/users', async (req, res) => {
  try {
    const [results] = await pool.promise().query(
      'SELECT user_id, username, role FROM users'
    ); // Nu trimitem parola în client
    res.json(results);
  } catch (err) {
    console.error('Eroare la listarea utilizatorilor:', err);
    res.status(500).send('Eroare server');
  }
});
// PUT /users/:user_id
// PUT /users/:user_id
router.put('/users/:user_id', async (req, res) => {
  const { user_id } = req.params;
  const { username, role, password } = req.body;

  try {
    let query = 'UPDATE users SET username = ?, role = ?';
    const params = [username, role];

    if (password) {
      const hashedPassword = await bcrypt.hash(password, 10);
      query += ', password = ?';
      params.push(hashedPassword);
    }

    query += ' WHERE user_id = ?';
    params.push(user_id);

    await pool.promise().query(query, params);
    res.sendStatus(200);
  } catch (err) {
    console.error('Eroare la actualizare utilizator:', err);
    res.status(500).send('Eroare server');
  }
});

// DELETE /users/:user_id
router.delete('/users/:user_id', async (req, res) => {
  const { user_id } = req.params;

  try {
    await pool.promise().query('DELETE FROM users WHERE user_id = ?', [user_id]);
    res.sendStatus(200);
  } catch (err) {
    console.error('Eroare la ștergerea utilizatorului:', err);
    res.status(500).send('Eroare server');
  }
});
const bcrypt = require('bcrypt');

// POST /users
router.post('/users', async (req, res) => {
  const { username, password, role } = req.body;

  try {
    const hashedPassword = await bcrypt.hash(password, 10);
    await pool.promise().query(
      'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
      [username, hashedPassword, role]
    );
    res.sendStatus(201);
  } catch (err) {
    console.error('Eroare la adăugare utilizator:', err);
    res.status(500).send('Eroare server');
  }
});

module.exports = router;