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();

// Get all bindings across all sites
router.get('/', authMw, (req, res) => {
  try {
    const raw = ps(`
      Import-Module WebAdministration;
      $result = @();
      Get-Website | ForEach-Object {
        $site = $_.Name;
        $_.Bindings.Collection | ForEach-Object {
          $result += [PSCustomObject]@{ Site=$site; Protocol=$_.protocol; Binding=$_.bindingInformation; SslFlags=$_.sslFlags }
        }
      };
      $result | 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 }); }
});

// Get site names for dropdown
router.get('/sites', authMw, (req, res) => {
  try {
    const raw = ps(`Import-Module WebAdministration; Get-Website | Select-Object Name | 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 }); }
});

// Add binding
router.post('/', authMw, (req, res) => {
  const { site, protocol, ip, port, hostname } = req.body;
  if (!site || !port) return res.status(400).json({ error:'Site and port are required' });
  try {
    ps(`Import-Module WebAdministration; New-WebBinding -Name '${site}' -Protocol '${protocol||'http'}' -IPAddress '${ip||'*'}' -Port ${parseInt(port)} -HostHeader '${hostname||''}'`);
    res.json({ ok:true });
  } catch(e) { res.status(500).json({ error:e.message }); }
});

// Remove binding
router.delete('/', authMw, (req, res) => {
  const { site, binding, protocol } = req.query;
  if (!site || !binding) return res.status(400).json({ error:'Site and binding required' });
  try {
    const parts = binding.split(':');
    const ip = parts[0]||'*', port = parts[1]||'80', host = parts[2]||'';
    ps(`Import-Module WebAdministration; Remove-WebBinding -Name '${site}' -Protocol '${protocol||'http'}' -IPAddress '${ip}' -Port ${port} -HostHeader '${host}'`);
    res.json({ ok:true });
  } catch(e) { res.status(500).json({ error:e.message }); }
});

module.exports = router;