const { Router } = require('express');
const bcrypt = require('bcryptjs');
const pool = require('../config/db');
const { authRequired, signToken } = require('../middlewares/auth');
const { logAction } = require('../services/audit');

const router = Router();

// LOGIN
router.post('/login', async (req, res) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) return res.status(400).json({ error: 'Email y contraseña requeridos' });

    // Rate limit
    const ip = req.ip;
    const [att] = await pool.query('SELECT COUNT(*) as c FROM login_attempts WHERE ip_address=? AND attempted_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)', [ip]);
    if (att[0].c >= 10) return res.status(429).json({ error: 'Demasiados intentos. Espera 15 min.' });

    const [users] = await pool.query('SELECT * FROM users WHERE email=?', [email]);
    if (!users.length) {
      await pool.query('INSERT INTO login_attempts (ip_address, email) VALUES (?,?)', [ip, email]);
      return res.status(401).json({ error: 'Credenciales inválidas' });
    }

    const user = users[0];
    const valid = await bcrypt.compare(password, user.password);
    if (!valid) {
      await pool.query('INSERT INTO login_attempts (ip_address, email) VALUES (?,?)', [ip, email]);
      return res.status(401).json({ error: 'Credenciales inválidas' });
    }
    if (!user.active) return res.status(403).json({ error: 'Cuenta desactivada' });

    const token = signToken({ sub: user.id, name: user.name, email: user.email, role: user.role });
    await pool.query('UPDATE users SET last_login=NOW() WHERE id=?', [user.id]);
    await logAction(user.id, user.name, 'login', 'user', user.id, null, null, ip);

    res.json({ token, user: { id: user.id, name: user.name, email: user.email, role: user.role, department: user.department } });
  } catch (err) {
    console.error('Login error:', err);
    res.status(500).json({ error: 'Error interno' });
  }
});

// ME
router.get('/me', authRequired, async (req, res) => {
  const [u] = await pool.query('SELECT id,name,email,role,department,phone,created_at FROM users WHERE id=?', [req.user.sub]);
  if (!u.length) return res.status(404).json({ error: 'No encontrado' });
  res.json(u[0]);
});

// UPDATE PROFILE
router.put('/profile', authRequired, async (req, res) => {
  const { name, phone, department } = req.body;
  await pool.query('UPDATE users SET name=?, phone=?, department=? WHERE id=?', [name, phone, department, req.user.sub]);
  res.json({ message: 'Perfil actualizado' });
});

// CHANGE PASSWORD
router.put('/password', authRequired, async (req, res) => {
  const { current_password, new_password } = req.body;
  if (!current_password || !new_password || new_password.length < 8) return res.status(400).json({ error: 'Contraseña actual y nueva (mín 8) requeridas' });
  const [u] = await pool.query('SELECT password FROM users WHERE id=?', [req.user.sub]);
  if (!await bcrypt.compare(current_password, u[0].password)) return res.status(400).json({ error: 'Contraseña actual incorrecta' });
  await pool.query('UPDATE users SET password=? WHERE id=?', [await bcrypt.hash(new_password, 10), req.user.sub]);
  res.json({ message: 'Contraseña actualizada' });
});

module.exports = router;
