const express      = require('express');
const { execSync } = require('child_process');
const router       = express.Router();
const authMw       = require('../middleware/auth');

const ps = (cmd, timeout = 30000) =>
  execSync(`powershell -ExecutionPolicy Bypass -Command "${cmd}"`, { timeout }).toString().trim();

// ── Security scan ──────────────────────────────────────────
router.get('/scan', authMw, (req, res) => {
  const results = [];
  const checks = [
    {
      id: 'firewall', category: 'Firewall', title: 'Windows Firewall enabled',
      cmd: `(Get-NetFirewallProfile | Where-Object {$_.Enabled -eq $false} | Measure-Object).Count -eq 0`,
      pass: 'True', detail: 'All firewall profiles are active', failDetail: 'One or more firewall profiles are disabled'
    },
    {
      id: 'rdp-port', category: 'Remote Access', title: 'RDP not on default port',
      cmd: `(Get-ItemProperty -Path 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -Name PortNumber -ErrorAction SilentlyContinue).PortNumber -ne 3389`,
      pass: 'True', detail: 'RDP is using a non-default port', failDetail: 'RDP is on default port 3389 — consider changing it',
      fix: 'disable-rdp-default'
    },
    {
      id: 'guest', category: 'Accounts', title: 'Guest account disabled',
      cmd: `(Get-LocalUser -Name Guest -ErrorAction SilentlyContinue).Enabled -eq $false`,
      pass: 'True', detail: 'Guest account is disabled', failDetail: 'Guest account is enabled — security risk',
      fix: 'disable-guest'
    },
    {
      id: 'defender', category: 'Antivirus', title: 'Windows Defender running',
      cmd: `(Get-Service WinDefend -ErrorAction SilentlyContinue).Status -eq 'Running'`,
      pass: 'True', detail: 'Windows Defender is active', failDetail: 'Windows Defender is not running'
    },
    {
      id: 'auto-update', category: 'Updates', title: 'Windows Update service running',
      cmd: `(Get-Service wuauserv -ErrorAction SilentlyContinue).Status -eq 'Running'`,
      pass: 'True', detail: 'Windows Update service is active', failDetail: 'Windows Update service is stopped'
    },
    {
      id: 'smb1', category: 'Protocols', title: 'SMBv1 disabled',
      cmd: `(Get-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -ErrorAction SilentlyContinue).State -ne 'Enabled'`,
      pass: 'True', detail: 'SMBv1 is disabled (good — prevents WannaCry etc.)', failDetail: 'SMBv1 is enabled — disable it to reduce attack surface',
      fix: 'disable-smb1'
    },
    {
      id: 'remote-reg', category: 'Services', title: 'Remote Registry service disabled',
      cmd: `(Get-Service RemoteRegistry -ErrorAction SilentlyContinue).StartType -eq 'Disabled'`,
      pass: 'True', detail: 'Remote Registry is disabled', failDetail: 'Remote Registry is not disabled — allows remote registry edits',
      fix: 'disable-remote-registry'
    },
    {
      id: 'audit-log', category: 'Logging', title: 'Security audit log enabled',
      cmd: `(Get-EventLog -LogName Security -Newest 1 -ErrorAction SilentlyContinue) -ne $null`,
      pass: 'True', detail: 'Security audit log is active', failDetail: 'Security audit log appears empty or disabled'
    }
  ];

  for (const check of checks) {
    let status = 'info', resultDetail = check.detail;
    try {
      const out = ps(check.cmd).trim();
      if (out === check.pass) {
        status = 'pass';
      } else {
        status = 'fail';
        resultDetail = check.failDetail;
      }
    } catch {
      status = 'warn';
      resultDetail = 'Could not check — run panel as Administrator';
    }
    results.push({ category: check.category, title: check.title, status, detail: resultDetail, fix: check.fix || null });
  }
  res.json(results);
});

// ── Apply fix ──────────────────────────────────────────────
router.post('/fix', authMw, (req, res) => {
  const { action } = req.body;
  const fixes = {
    'disable-guest':           `Disable-LocalUser -Name Guest`,
    'disable-smb1':            `Disable-WindowsOptionalFeature -Online -FeatureName SMB1Protocol -NoRestart`,
    'disable-remote-registry': `Set-Service RemoteRegistry -StartupType Disabled; Stop-Service RemoteRegistry -Force -ErrorAction SilentlyContinue`,
    'disable-rdp-default':     `Set-ItemProperty -Path 'HKLM:\\System\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp' -Name PortNumber -Value 13389`
  };
  if (!fixes[action]) return res.status(400).json({ error: 'Unknown fix action' });
  try {
    ps(fixes[action], 60000);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── List listening ports ───────────────────────────────────
router.get('/open-ports', authMw, (req, res) => {
  try {
    const raw = ps(`
      Get-NetTCPConnection -State Listen |
      Select-Object LocalPort,
        @{N='Process';E={(Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName}} |
      Sort-Object LocalPort -Unique | 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 }); }
});

// ── Open a firewall port ───────────────────────────────────
router.post('/open-port', authMw, (req, res) => {
  const { port, protocol, name } = req.body;
  if (!port) return res.status(400).json({ error: 'Port required' });
  const ruleName = name || `ServerPanel-Allow-${protocol||'TCP'}-${port}`;
  try {
    ps(`New-NetFirewallRule -DisplayName '${ruleName}' -Direction Inbound -Action Allow -Protocol ${protocol||'TCP'} -LocalPort ${parseInt(port)} -Enabled True`);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

// ── Block a firewall port ──────────────────────────────────
router.post('/block-port', authMw, (req, res) => {
  const { port, protocol } = req.body;
  if (!port) return res.status(400).json({ error: 'Port required' });
  const ruleName = `ServerPanel-Block-${protocol||'TCP'}-${port}`;
  try {
    ps(`New-NetFirewallRule -DisplayName '${ruleName}' -Direction Inbound -Action Block -Protocol ${protocol||'TCP'} -LocalPort ${parseInt(port)} -Enabled True`);
    res.json({ ok: true });
  } catch(e) { res.status(500).json({ error: e.message }); }
});

module.exports = router;