const router = require('express').Router();
const bcrypt = require('bcryptjs');
const { usersDb } = require('../lib/db');
const { sign, authMiddleware }    = require('../lib/auth');

// POST /api/auth/login
router.post('/login', (req, res) => {
  const { empId, password } = req.body;
  if (!empId || !password)
    return res.status(400).json({ error: 'empId and password are required' });

  const user = usersDb.get('users').find({ empId: empId.toUpperCase() }).value();
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });
  if (!bcrypt.compareSync(password, user.password))
    return res.status(401).json({ error: 'Invalid credentials' });

  const token = sign({
    id: user.id, empId: user.empId, role: user.role, name: user.name
  });
  const { password: _, ...safe } = user;
  res.json({ token, user: safe });
});

// POST /api/auth/change-password  (authenticated user changes own password)
router.post('/change-password', authMiddleware, (req, res) => {
  const { currentPassword, newPassword } = req.body;
  if (!currentPassword || !newPassword)
    return res.status(400).json({ error: 'currentPassword and newPassword are required' });
  if (newPassword.length < 6)
    return res.status(400).json({ error: 'New password must be at least 6 characters' });

  const user = usersDb.get('users').find({ empId: req.user.empId }).value();
  if (!user) return res.status(404).json({ error: 'User not found' });
  if (!bcrypt.compareSync(currentPassword, user.password))
    return res.status(401).json({ error: 'Current password is incorrect' });

  const hashed = bcrypt.hashSync(newPassword, 10);
  usersDb.get('users').find({ empId: req.user.empId }).assign({ password: hashed }).write();
  res.json({ message: 'Password changed successfully' });
});

// GET /api/auth/verify  — verify token and return user (used for session restore on reload)
router.get('/verify', authMiddleware, (req, res) => {
  const user = usersDb.get('users').find({ empId: req.user.empId }).value();
  if (!user) return res.status(404).json({ error: 'User not found' });
  const { password: _, ...safe } = user;
  res.json({ valid: true, user: safe });
});

module.exports = router;
