const express    = require('express');
const router     = express.Router();
const jwt        = require('jsonwebtoken');
const bcrypt     = require('bcryptjs');
const { getUsers }  = require('../services/users');
const { logLogin }  = require('../services/logs');

// POST /api/auth/login
router.post('/login', async (req, res) => {
  const { username, password } = req.body || {};
  const ip = req.ip || req.socket?.remoteAddress || null;

  const user = getUsers().find(u => u.username === username);

  if (!user) {
    logLogin({ username: username || '?', role: null, ip, success: false });
    return res.status(401).json({ error: 'Identifiants invalides' });
  }

  const valid = await bcrypt.compare(password || '', user.password);
  if (!valid) {
    logLogin({ username, role: user.role, ip, success: false });
    return res.status(401).json({ error: 'Identifiants invalides' });
  }

  logLogin({ username, role: user.role, ip, success: true });

  const token = jwt.sign(
    { sub: user.username, id: user.id, username: user.username, role: user.role, region: user.region },
    process.env.JWT_SECRET,
    { expiresIn: '8h' }
  );

  res.json({ token });
});

module.exports = router;
