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}"`,
  { timeout: 15000 }
).toString().trim();

router.get('/', authMw, (req, res) => {
  const page    = Math.max(1, parseInt(req.query.page)  || 1);
  const perPage = Math.min(20, parseInt(req.query.per)  || 20);
  const skip    = (page - 1) * perPage;
  const fetch   = skip + perPage; // fetch only what we need

  try {
    // Get total count separately (fast — no data transfer)
    const countRaw = ps(`(Get-Process | Measure-Object).Count`);
    const total    = parseInt(countRaw) || 0;

    // Fetch only the page we need
    const raw = ps(
      `Get-Process | Select-Object Id,ProcessName,CPU,WorkingSet,Handles | ` +
      `Sort-Object CPU -Descending | Select-Object -Skip ${skip} -First ${perPage} | ConvertTo-Json`
    );

    const list = raw ? JSON.parse(raw) : [];
    res.json({
      data:      Array.isArray(list) ? list : [list],
      total:     total,
      page:      page,
      perPage:   perPage,
      totalPages: Math.ceil(total / perPage)
    });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

router.delete('/:pid', authMw, (req, res) => {
  try {
    ps(`Stop-Process -Id ${parseInt(req.params.pid)} -Force`);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;