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

function nowTime() {
  return new Date().toLocaleTimeString('en-IN',{hour:'2-digit',minute:'2-digit',hour12:true});
}
function todayStr() { return new Date().toISOString().slice(0,10); }

// GET /api/leave
router.get('/', authMiddleware, (req, res) => {
  const all = leaveDb.get('requests').value();
  if (req.user.role === 'admin') return res.json(all);
  res.json(all.filter(r => r.empId === req.user.empId));
});

// POST /api/leave  (employee applies)
router.post('/', authMiddleware, (req, res) => {
  const { type, from, to, reason } = req.body;
  if (!type || !from || !to || !reason)
    return res.status(400).json({ error: 'All fields required' });

  const emp = usersDb.get('users').find({ empId: req.user.empId }).value();
  const request = {
    id: uuidv4(),
    empId: req.user.empId,
    name: emp ? emp.name : req.user.name,
    type, from, to, reason,
    status: 'pending',
    appliedOn: todayStr(),
    createdAt: new Date().toISOString()
  };
  leaveDb.get('requests').push(request).write();
  res.status(201).json(request);
});

// PUT /api/leave/:id  (admin approves/rejects)
router.put('/:id', authMiddleware, adminOnly, (req, res) => {
  const { status } = req.body;
  if (!['approved','rejected'].includes(status))
    return res.status(400).json({ error: 'Status must be approved or rejected' });

  const record = leaveDb.get('requests').find({ id: req.params.id }).value();
  if (!record) return res.status(404).json({ error: 'Leave request not found' });

  leaveDb.get('requests').find({ id: req.params.id }).assign({ status }).write();

  // Notify employee via messages
  const msg = {
    id: uuidv4(), from: 'ADMIN',
    text: `🗓️ Your ${record.type} request (${record.from} → ${record.to}) has been ${status === 'approved' ? '✅ Approved' : '❌ Rejected'}.`,
    time: nowTime(), date: todayStr(), createdAt: new Date().toISOString()
  };
  const thread = messagesDb.get('threads').find({ empId: record.empId }).value();
  if (thread) {
    messagesDb.get('threads').find({ empId: record.empId }).get('messages').push(msg).write();
  } else {
    messagesDb.get('threads').push({ empId: record.empId, messages: [msg] }).write();
  }

  res.json(leaveDb.get('requests').find({ id: req.params.id }).value());
});

// DELETE /api/leave/:id
router.delete('/:id', authMiddleware, (req, res) => {
  const record = leaveDb.get('requests').find({ id: req.params.id }).value();
  if (!record) return res.status(404).json({ error: 'Not found' });
  if (req.user.role !== 'admin' && record.empId !== req.user.empId)
    return res.status(403).json({ error: 'Forbidden' });
  leaveDb.get('requests').remove({ id: req.params.id }).write();
  res.json({ message: 'Deleted' });
});

module.exports = router;
