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

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

// win-acme default install path
const WACS_PATHS = [
  'C:\\win-acme\\wacs.exe',
  'C:\\tools\\win-acme\\wacs.exe',
  'C:\\Program Files\\win-acme\\wacs.exe',
];

function findWacs() {
  for (const p of WACS_PATHS) {
    try { if (fs.existsSync(p)) return p; } catch {}
  }
  // also check PATH
  try {
    const found = ps(`(Get-Command wacs.exe -ErrorAction SilentlyContinue).Source`);
    if (found && found.trim()) return found.trim();
  } catch {}
  return null;
}

// ── Check win-acme installed ───────────────────────────
router.get('/status', authMw, (req, res) => {
  const wacs = findWacs();
  res.json({ installed: !!wacs, path: wacs });
});

// ── Install win-acme via Chocolatey ───────────────────
router.post('/install', authMw, (req, res) => {
  res.json({ ok: true, message: 'Installing win-acme in background...' });
  exec(
    `powershell -ExecutionPolicy Bypass -Command "if(!(Get-Command choco -ErrorAction SilentlyContinue)){iex((New-Object Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))} choco install win-acme -y --no-progress"`,
    { timeout: 10 * 60 * 1000 },
    (err) => {
      if (err) console.error('[letsencrypt] install failed:', err.message);
      else     console.log('[letsencrypt] win-acme installed');
    }
  );
});

// ── List managed certificates ─────────────────────────
router.get('/certs', authMw, (req, res) => {
  const wacs = findWacs();
  if (!wacs) return res.json([]);
  try {
    const raw = ps(`& '${wacs}' --list --json 2>$null`);
    if (!raw) return res.json([]);
    try { res.json(JSON.parse(raw)); } catch { res.json([]); }
  } catch { res.json([]); }
});

// ── Request certificate ────────────────────────────────
router.post('/request', authMw, (req, res) => {
  const { domain, email, siteName, validation } = req.body;
  if (!domain) return res.status(400).json({ error: 'Domain is required' });
  if (!email)  return res.status(400).json({ error: 'Email is required' });

  const wacs = findWacs();
  if (!wacs) return res.status(400).json({ error: 'win-acme is not installed. Install it first.' });

  // Respond immediately — certificate issuance takes 30-120 seconds
  res.json({ ok: true, message: `Certificate request started for ${domain}. This runs in the background and may take 1–2 minutes.` });

  const validationType = validation || 'http-01';
  let wacsArgs = `--target manual --host "${domain}" --emailaddress "${email}" --accepttos --store pemfiles`;

  // If IIS site specified, use IIS validation and binding
  if (siteName) {
    wacsArgs = `--target iis --siteid "${siteName}" --host "${domain}" --emailaddress "${email}" --accepttos`;
  }

  exec(
    `"${wacs}" ${wacsArgs}`,
    { timeout: 5 * 60 * 1000 },
    (err, stdout, stderr) => {
      if (err) console.error('[letsencrypt] request failed:', err.message, stderr);
      else     console.log('[letsencrypt] cert issued for', domain, stdout);
    }
  );
});

// ── Renew all ──────────────────────────────────────────
router.post('/renew', authMw, (req, res) => {
  const wacs = findWacs();
  if (!wacs) return res.status(400).json({ error: 'win-acme not installed' });

  res.json({ ok: true, message: 'Renewal started in background' });
  exec(`"${wacs}" --renew --force`, { timeout: 5 * 60 * 1000 }, (err) => {
    if (err) console.error('[letsencrypt] renew failed:', err.message);
    else     console.log('[letsencrypt] renewal complete');
  });
});

module.exports = router;