'use strict';

const { auditSecurityConfig } = require('./audit');
const { validateSandboxPolicy } = require('./sandbox-policy');

function runSecurityDoctor(config = {}) {
  const audit = auditSecurityConfig(config);
  const sandbox = validateSandboxPolicy(config.sandbox || config.sandboxPolicy || {});
  const findings = [
    ...(audit.findings || []),
    ...(sandbox.findings || []),
  ];
  const summary = summarize(findings);
  return {
    ok: summary.high === 0 && summary.critical === 0,
    summary,
    findings,
    sections: {
      audit,
      sandbox,
    },
  };
}

function summarize(findings = []) {
  return findings.reduce((acc, item) => {
    const severity = item.severity || 'low';
    acc[severity] = (acc[severity] || 0) + 1;
    acc.total += 1;
    return acc;
  }, { critical: 0, high: 0, medium: 0, low: 0, total: 0 });
}

module.exports = {
  runSecurityDoctor,
};
