const http = require('http');

function checkService(host, port, path, timeout = 3000) {
  return new Promise((resolve) => {
    const req = http.request({ hostname: host, port, path, method: 'GET', timeout }, (res) => {
      resolve({ online: res.statusCode < 500, status: res.statusCode });
    });
    req.on('error', () => resolve({ online: false, status: 0 }));
    req.on('timeout', () => { req.destroy(); resolve({ online: false, status: 0 }); });
    req.end();
  });
}

async function getServicesStatus() {
  const qsHost = process.env.QS_HOST || 'python-quality';
  const [quality, designer, leadgen] = await Promise.all([
    checkService(qsHost, 3002, '/python-quality/'),
    checkService('python-designer', 3001, '/python-editor/'),
    checkService('python-leadgen', 3003, '/python-leadgen/health')
  ]);
  return {
    consulting: { online: true, label: 'Mek-Tech Core', port: 3000 },
    quality: { ...quality, label: 'Data Quality', port: 3002 },
    designer: { ...designer, label: 'Pro Designer', port: 3001 },
    leadgen: { ...leadgen, label: 'Lead Generation', port: 3003 }
  };
}

module.exports = { checkService, getServicesStatus };
