#!/usr/bin/env node

require('../lib/environment-helper')

const db = require('../lib/db')
const machineLoader = require('../lib/machine-loader')
const operator = require('../lib/operator')

console.log('Running diagnostics on all paired devices...\n')

operator.getOperatorId('middleware')
  .then(operatorId => {
    if (!operatorId) {
      throw new Error('Operator ID not found in database')
    }
    
    return db.any('SELECT device_id, name FROM devices')
      .then(devices => ({ operatorId, devices }))
  })
  .then(({ operatorId, devices }) => {
    if (devices.length === 0) {
      console.log('No paired devices found.')
      process.exit(0)
    }

    const deviceIds = devices.map(d => d.device_id)
    return machineLoader.batchDiagnostics(deviceIds, operatorId)
  })
  .then(() => {
    console.log('\n✓ Diagnostics initiated for all devices. It can take a few minutes for the results to appear on the admin.')
    process.exit(0)
  })
  .catch(err => {
    console.error('Error:', err.message)
    process.exit(1)
  })