const express      = require('express');
const { execSync } = require('child_process');
const router       = express.Router();
const authMw       = require('../middleware/auth');
const ps = (cmd) => execSync(`powershell -ExecutionPolicy Bypass -Command "${cmd}"`).toString().trim();
router.get('/', authMw, (req, res) => {
  try {
    const raw = ps(`Get-Service | Select-Object Name,DisplayName,Status,StartType | ConvertTo-Json`);
    res.json(JSON.parse(raw));
  } catch(e) { res.status(500).json({ error: e.message }); }
});
router.post('/:name/start',   authMw, (req, res) => { ps(`Start-Service ${req.params.name}`);   res.json({ ok: true }); });
router.post('/:name/stop',    authMw, (req, res) => { ps(`Stop-Service ${req.params.name}`);    res.json({ ok: true }); });
router.post('/:name/restart', authMw, (req, res) => { ps(`Restart-Service ${req.params.name}`); res.json({ ok: true }); });
sCacheClear('services');

module.exports = router;