// Registers SincA_WA_Baileys as a Windows service (auto-start on boot,
// auto-restart on crash). No exe build required — the service runs
// `node main.js` directly.
//
// Run ONCE per PC from an ELEVATED (Administrator) shell:
//     node service/install-service.js
//
// If you ship a portable node.exe with the folder, run it with that node so
// the service is registered to use it:
//     .\node.exe service\install-service.js
const path = require('path');
const { Service } = require('node-windows');

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

const svc = new Service({
    name: 'SincA WhatsApp Service',
    description: 'SincA WhatsApp (Baileys / no Chromium) background service — HTTP API on 12301, status to SincA on 12302.',
    script: path.join(ROOT, 'main.js'),
    workingDirectory: ROOT,
    // Use the same node that runs this installer (supports a portable node.exe
    // shipped alongside the app, with no Node installed system-wide).
    execPath: process.execPath,
    // Crash recovery: wait 2s, back off by 25%, cap the restart window.
    wait: 2,
    grow: 0.25,
    maxRestarts: 20,
    // Persisted in the generated service wrapper; matches .env defaults.
    env: [
        { name: 'HTTP_PORT', value: process.env.HTTP_PORT || '12301' },
        { name: 'WA_DEBUG', value: process.env.WA_DEBUG || 'false' },
    ],
});

svc.on('install', () => {
    console.log('✅ Service installed. Starting…');
    svc.start();
});
svc.on('alreadyinstalled', () => {
    console.log('ℹ️  Service already installed. Run service/uninstall-service.js first to reinstall.');
    process.exit(0);
});
svc.on('start', () => {
    console.log('✅ "SincA WhatsApp Service" is running.');
    console.log('   API for SincA: http://localhost:' + (process.env.HTTP_PORT || '12301') + '/v1');
    console.log('   Logs: ' + path.join(ROOT, 'service', 'daemon'));
});
svc.on('error', (err) => {
    console.error('❌ Service error:', err);
});

console.log('Installing "SincA WhatsApp Service" using node at:', process.execPath);
console.log('App entry:', path.join(ROOT, 'main.js'));
svc.install();
