const router = require('express').Router();
const { messagesDb, uuidv4 } = require('../lib/db');
const { authMiddleware } = 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/messages  — admin gets all threads, employee gets own
router.get('/', authMiddleware, (req, res) => {
  const threads = messagesDb.get('threads').value();
  if (req.user.role === 'admin') return res.json(threads);
  const thread = threads.find(t => t.empId === req.user.empId);
  res.json(thread ? [thread] : [{ empId: req.user.empId, messages: [] }]);
});

// GET /api/messages/:empId  — get one thread
router.get('/:empId', authMiddleware, (req, res) => {
  const empId = req.params.empId.toUpperCase();
  if (req.user.role !== 'admin' && req.user.empId !== empId)
    return res.status(403).json({ error: 'Forbidden' });
  const thread = messagesDb.get('threads').find({ empId }).value();
  res.json(thread || { empId, messages: [] });
});

// POST /api/messages/:empId  — send a message
router.post('/:empId', authMiddleware, (req, res) => {
  const empId = req.params.empId.toUpperCase();
  const { text } = req.body;
  if (!text) return res.status(400).json({ error: 'text is required' });

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

  const msg = {
    id: uuidv4(),
    from: req.user.role === 'admin' ? 'ADMIN' : empId,
    text,
    time: nowTime(),
    date: todayStr(),
    createdAt: new Date().toISOString()
  };

  const thread = messagesDb.get('threads').find({ empId }).value();
  if (thread) {
    messagesDb.get('threads').find({ empId }).get('messages').push(msg).write();
  } else {
    messagesDb.get('threads').push({ empId, messages: [msg] }).write();
  }
  res.status(201).json(msg);
});

module.exports = router;
