import { Router } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { upgradeService } from './upgrade.service';

const router = Router();

// All routes require SUPER_ADMIN
router.use(authenticate, requireRole('SUPER_ADMIN'));

/**
 * GET /api/upgrade/status
 * Returns combined status: version info, progress (if running), and last result.
 */
router.get('/status', (_req, res) => {
  const status = upgradeService.getStatus();
  const progress = upgradeService.getProgress();
  const result = upgradeService.getResult();
  const running = upgradeService.isRunning();
  const watcher = upgradeService.getWatcherHealth();

  res.json({ status, progress: running ? progress : null, result, running, watcher });
});

/**
 * POST /api/upgrade/check
 * Triggers an update check (writes trigger.json for systemd watcher).
 */
router.post('/check', (req, res) => {
  try {
    const userEmail = req.user?.email || 'unknown';
    upgradeService.triggerCheck(userEmail);
    res.json({ message: 'Update check triggered' });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to trigger check';
    res.status(409).json({ error: { message, code: 'UPGRADE_BUSY' } });
  }
});

/**
 * POST /api/upgrade/start
 * Triggers an upgrade (writes trigger.json for systemd watcher).
 * Body: { skipBackup?: boolean, pullServices?: boolean, dryRun?: boolean, useRegistry?: boolean }
 */
router.post('/start', (req, res) => {
  try {
    const userEmail = req.user?.email || 'unknown';
    const { skipBackup, pullServices, dryRun, useRegistry } = req.body as {
      skipBackup?: boolean;
      pullServices?: boolean;
      dryRun?: boolean;
      useRegistry?: boolean;
    };
    upgradeService.triggerUpgrade(userEmail, { skipBackup, pullServices, dryRun, useRegistry });
    res.json({ message: 'Upgrade triggered' });
  } catch (err) {
    const message = err instanceof Error ? err.message : 'Failed to trigger upgrade';
    res.status(409).json({ error: { message, code: 'UPGRADE_BUSY' } });
  }
});

/**
 * GET /api/upgrade/history
 * Returns the history of past upgrade results (newest first).
 */
router.get('/history', (_req, res) => {
  const history = upgradeService.getHistory();
  res.json({ history });
});

/**
 * POST /api/upgrade/clear-result
 * Removes the last upgrade result file.
 */
router.post('/clear-result', (_req, res) => {
  upgradeService.clearResult();
  res.json({ message: 'Result cleared' });
});

export { router as upgradeRouter };
