'use strict';
/**
 * DeployPro — Windows Service Installer
 * Run this script as Administrator:
 *   node service\install.js
 */

const path    = require('path');
const Service = require('node-windows').Service;

const ROOT = path.resolve(__dirname, '..');

const svc = new Service({
  name:        'DeployPro',
  id:          'DeployPro',
  description: 'DeployPro Enterprise IIS Deployment Pipeline (Node.js web server on port 7070)',
  script:       path.join(ROOT, 'server.js'),
  nodeOptions: [],
  env: [
    { name: 'NODE_ENV', value: 'production' },
    { name: 'PORT',     value: '7070'       },
  ],
  // Restart policy
  wait:         2,      // seconds before first restart
  grow:         0.5,    // growth factor for subsequent restarts
  maxRestarts:  5,      // max consecutive restarts
  abortOnError: false,  // don't give up on repeated errors
});

svc.on('install', () => {
  console.log('\n[DeployPro] Service installed successfully.');
  console.log('[DeployPro] Starting service...');
  svc.start();
});

svc.on('start', () => {
  console.log('[DeployPro] Service started.');
  console.log('[DeployPro] Access the application at: http://localhost:7070');
  console.log('\nTo manage the service:');
  console.log('  Start:     net start DeployPro');
  console.log('  Stop:      net stop  DeployPro');
  console.log('  URL:       http://localhost:7070');
  console.log('  Uninstall: node service\\uninstall.js');
  process.exit(0);
});

svc.on('alreadyinstalled', () => {
  console.log('\n[DeployPro] Service is already installed.');
  console.log('  To reinstall, first run: node service\\uninstall.js');
  process.exit(1);
});

svc.on('invalidinstallation', () => {
  console.error('[DeployPro] Invalid installation detected. Try uninstalling first.');
  process.exit(1);
});

svc.on('error', (err) => {
  console.error('[DeployPro] Service error:', err);
  process.exit(1);
});

console.log('\n╔══════════════════════════════════════════╗');
console.log('║  DeployPro — Windows Service Installer   ║');
console.log('╚══════════════════════════════════════════╝\n');
console.log(`[DeployPro] Installing service from: ${ROOT}`);
console.log('[DeployPro] Service name: DeployPro');
console.log('[DeployPro] Port: 7070\n');

svc.install();
