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-ChildItem -Path Cert:\\LocalMachine\\My |
      Select-Object Subject, Thumbprint, NotBefore, NotAfter, Issuer |
      ConvertTo-Json
    `);
    if (!raw) return res.json([]);
    const list = JSON.parse(raw);
    res.json(Array.isArray(list) ? list : [list]);
  } catch(e) { res.status(500).json({ error: e.message }); }
});

router.delete('/:thumbprint', authMw, (req, res) => {
  try {
    ps(`Remove-Item -Path Cert:\\LocalMachine\\My\\${req.params.thumbprint}`);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;