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

function todayStr() { return new Date().toISOString().slice(0,10); }

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

// POST /api/reports  (employee submits)
router.post('/', authMiddleware, (req, res) => {
  const { clockIn, clockOut, totalHours, tasksDone, tasksProgress, remarks, status, date } = req.body;
  const emp = usersDb.get('users').find({ empId: req.user.empId }).value();
  const report = {
    id: uuidv4(),
    empId: req.user.empId,
    name: emp ? emp.name : req.user.name,
    dept: emp ? emp.dept : '',
    pos:  emp ? emp.pos  : '',
    date: date || todayStr(),
    clockIn:  clockIn  || '—',
    clockOut: clockOut || '—',
    totalHours: totalHours || '—',
    tasksDone:     Array.isArray(tasksDone)     ? tasksDone     : (tasksDone     ? [tasksDone]     : []),
    tasksProgress: Array.isArray(tasksProgress) ? tasksProgress : (tasksProgress ? [tasksProgress] : []),
    remarks:  remarks  || '',
    feedback: '',
    status:   status   || 'Present',
    createdAt: new Date().toISOString()
  };
  reportsDb.get('reports').push(report).write();
  res.status(201).json(report);
});

// PUT /api/reports/:id/feedback  (admin adds remark)
router.put('/:id/feedback', authMiddleware, adminOnly, (req, res) => {
  const { feedback } = req.body;
  const record = reportsDb.get('reports').find({ id: req.params.id }).value();
  if (!record) return res.status(404).json({ error: 'Report not found' });
  reportsDb.get('reports').find({ id: req.params.id }).assign({ feedback: feedback || '' }).write();
  res.json(reportsDb.get('reports').find({ id: req.params.id }).value());
});

// DELETE /api/reports/:id  (admin only)
router.delete('/:id', authMiddleware, adminOnly, (req, res) => {
  reportsDb.get('reports').remove({ id: req.params.id }).write();
  res.json({ message: 'Deleted' });
});

module.exports = router;
