const express  = require('express');
const router   = express.Router();
const bcrypt   = require('bcryptjs');
const { getUsers, saveUsers } = require('../services/users');

// GET /api/users — liste sans mot de passe
router.get('/', (req, res) => {
  const users = getUsers().map(({ password, ...u }) => u);
  res.json(users);
});

// POST /api/users — créer un utilisateur
router.post('/', async (req, res) => {
  const { username, password, role = 'user', region = 'all' } = req.body || {};

  if (!username || !password) {
    return res.status(400).json({ error: 'username et password requis' });
  }

  const users = getUsers();
  if (users.find(u => u.username === username)) {
    return res.status(409).json({ error: 'Identifiant déjà utilisé' });
  }

  const id   = Math.max(0, ...users.map(u => u.id || 0)) + 1;
  const hash = await bcrypt.hash(password, 10);
  const newUser = { id, username, password: hash, role, region };

  users.push(newUser);
  saveUsers(users);

  res.status(201).json({ id, username, role, region });
});

// DELETE /api/users/:id — supprimer un utilisateur
router.delete('/:id', (req, res) => {
  const id    = parseInt(req.params.id, 10);
  const users = getUsers();
  const idx   = users.findIndex(u => u.id === id);

  if (idx === -1) {
    return res.status(404).json({ error: 'Utilisateur introuvable' });
  }
  if (users[idx].username === req.user.username) {
    return res.status(400).json({ error: 'Impossible de supprimer son propre compte' });
  }

  users.splice(idx, 1);
  saveUsers(users);
  res.json({ ok: true });
});

module.exports = router;
