const express = require('express');
const router = express.Router();
const { exec } = require('child_process');
const fs = require('fs');

/**
 * System Routes - Maintenance & Deployment
 * 
 * POST /admin/system/deploy - Deploy latest Arbiter code from Gitea
 */

// POST /admin/system/deploy - Pull latest code and restart Arbiter
router.post('/deploy', (req, res) => {
    const username = req.user?.username || 'unknown';
    
    console.log(`[DEPLOY] Deployment initiated by ${username}`);
    
    // Use nohup to detach the process so the response returns before Arbiter restarts
    // Output goes to /tmp/deploy.log for debugging if needed
    exec(`nohup sudo /opt/scripts/deploy-arbiter.sh "${username}" > /tmp/deploy.log 2>&1 &`);
    
    // Return immediately - deploy happens in background
    res.json({ 
        success: true, 
        message: 'Deploy started. Arbiter will restart momentarily.'
    });
});

// GET /admin/system/status - Check if deploy script exists and arbiter is running
router.get('/status', (req, res) => {
    exec('systemctl is-active arbiter-3', (error, stdout) => {
        const isRunning = stdout.trim() === 'active';
        res.json({
            arbiter: isRunning ? 'running' : 'stopped',
            deployAvailable: fs.existsSync('/opt/scripts/deploy-arbiter.sh')
        });
    });
});

module.exports = router;
