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

// GET /api/employees
router.get('/', authMiddleware, (req, res) => {
  const users = usersDb.get('users').value();
  if (req.user.role === 'admin') {
    return res.json(users.filter(u => u.role !== 'admin').map(({ password, ...u }) => u));
  }
  const self = users.find(u => u.id === req.user.id);
  if (!self) return res.status(404).json({ error: 'Not found' });
  const { password, ...safe } = self;
  res.json([safe]);
});

// GET /api/employees/:empId
router.get('/:empId', authMiddleware, (req, res) => {
  const user = usersDb.get('users').find({ empId: req.params.empId.toUpperCase() }).value();
  if (!user) return res.status(404).json({ error: 'Employee not found' });
  if (req.user.role !== 'admin' && req.user.empId !== req.params.empId.toUpperCase())
    return res.status(403).json({ error: 'Forbidden' });
  const { password, ...safe } = user;
  res.json(safe);
});

// POST /api/employees  (admin only)
router.post('/', authMiddleware, adminOnly, (req, res) => {
  const { name, empId, phone, email, dept, pos, password, doj, photo } = req.body;
  if (!name || !empId || !email || !password || !dept || !pos)
    return res.status(400).json({ error: 'Missing required fields' });

  if (usersDb.get('users').find({ empId: empId.toUpperCase() }).value())
    return res.status(409).json({ error: 'Employee ID already exists' });

  const newUser = {
    id: uuidv4(), empId: empId.toUpperCase(),
    name, phone: phone || '', email, dept, pos,
    photo: photo || null, doj: doj || '',
    role: 'employee',
    password: bcrypt.hashSync(password, 10),
    createdAt: new Date().toISOString()
  };
  usersDb.get('users').push(newUser).write();
  const { password: _, ...safe } = newUser;
  res.status(201).json(safe);
});

// PUT /api/employees/:empId
router.put('/:empId', authMiddleware, (req, res) => {
  const target = usersDb.get('users').find({ empId: req.params.empId.toUpperCase() }).value();
  if (!target) return res.status(404).json({ error: 'Not found' });

  const isAdmin = req.user.role === 'admin';
  const isSelf  = req.user.empId === req.params.empId.toUpperCase();
  if (!isAdmin && !isSelf) return res.status(403).json({ error: 'Forbidden' });

  const { name, phone, email, dept, pos, doj, photo, password } = req.body;
  const updates = {};
  if (name)  updates.name  = name;
  if (phone !== undefined) updates.phone = phone;
  if (email) updates.email = email;
  if (isAdmin && dept) updates.dept = dept;
  if (isAdmin && pos)  updates.pos  = pos;
  if (isAdmin && doj !== undefined) updates.doj = doj;
  if (photo !== undefined) updates.photo = photo;
  if (password) updates.password = bcrypt.hashSync(password, 10);

  usersDb.get('users').find({ empId: req.params.empId.toUpperCase() }).assign(updates).write();
  const updated = usersDb.get('users').find({ empId: req.params.empId.toUpperCase() }).value();
  const { password: _, ...safe } = updated;
  res.json(safe);
});

// DELETE /api/employees/:empId  (admin only)
router.delete('/:empId', authMiddleware, adminOnly, (req, res) => {
  if (!usersDb.get('users').find({ empId: req.params.empId.toUpperCase() }).value())
    return res.status(404).json({ error: 'Not found' });
  usersDb.get('users').remove({ empId: req.params.empId.toUpperCase() }).write();
  res.json({ message: 'Employee deleted' });
});

module.exports = router;
