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

// GET /api/data/export  —  download full JSON backup
router.get('/export', authMiddleware, adminOnly, (req, res) => {
  const backup = {
    exportedAt: new Date().toISOString(),
    version: '1.0',
    users:    usersDb.get('users').value(),
    leave:    leaveDb.get('requests').value(),
    reports:  reportsDb.get('reports').value(),
    messages: messagesDb.get('threads').value(),
    salary:   salaryDb.get('slips').value(),
    tests:    testsDb.get('tests').value(),
    results:  testsDb.get('results').value()
  };
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Disposition', `attachment; filename="auxis_backup_${new Date().toISOString().slice(0,10)}.json"`);
  res.json(backup);
});

// POST /api/data/import  —  restore from JSON backup
router.post('/import', authMiddleware, adminOnly, (req, res) => {
  const data = req.body;
  if (!data || typeof data !== 'object') {
    return res.status(400).json({ error: 'Invalid backup data' });
  }
  try {
    if (Array.isArray(data.users))    usersDb.set('users', data.users).write();
    if (Array.isArray(data.leave))    leaveDb.set('requests', data.leave).write();
    if (Array.isArray(data.reports))  reportsDb.set('reports', data.reports).write();
    if (Array.isArray(data.messages)) messagesDb.set('threads', data.messages).write();
    if (Array.isArray(data.salary))   salaryDb.set('slips', data.salary).write();
    if (Array.isArray(data.tests))    testsDb.set('tests', data.tests).write();
    if (Array.isArray(data.results))  testsDb.set('results', data.results).write();
    res.json({ message: 'Data imported successfully' });
  } catch (e) {
    res.status(500).json({ error: 'Import failed: ' + e.message });
  }
});

// DELETE /api/data/clear  —  wipe all data (keep admin account)
router.delete('/clear', authMiddleware, adminOnly, (req, res) => {
  try {
    // Keep only admin users
    const admins = usersDb.get('users').filter({ role: 'admin' }).value();
    usersDb.set('users', admins).write();
    leaveDb.set('requests', []).write();
    reportsDb.set('reports', []).write();
    messagesDb.set('threads', []).write();
    salaryDb.set('slips', []).write();
    testsDb.set('tests', []).write();
    testsDb.set('results', []).write();
    res.json({ message: 'All data cleared. Admin account preserved.' });
  } catch (e) {
    res.status(500).json({ error: 'Clear failed: ' + e.message });
  }
});

module.exports = router;
