// RBE IAMMETER MQTT listener.
// Configure credentials through environment variables before use.

const mqtt = require('mqtt');

const HOST = process.env.RBE_MQTT_HOST || 'mqtt://mqtt.iammeter.com:8883';
const USERNAME = process.env.RBE_MQTT_USERNAME || 'CHANGE_ME_MQTT_USERNAME';
const PASSWORD = process.env.RBE_MQTT_PASSWORD || 'CHANGE_ME_MQTT_PASSWORD';
const CLIENT_ID = process.env.RBE_MQTT_CLIENT_ID || 'CHANGE_ME_RBE_MQTT_CLIENT_ID';

const options = {
  username: USERNAME,
  password: PASSWORD,
  clientId: CLIENT_ID,
  reconnectPeriod: 5000
};

const client = mqtt.connect(HOST, options);

client.on('connect', () => {
  console.log(`Connected to IAMMETER MQTT as "${CLIENT_ID}"`);
  client.subscribe('#', (err) => {
    if (err) console.error('Subscribe error:', err.message);
    else console.log('Subscribed to configured MQTT account topics.');
  });
});

client.on('message', (topic, message) => {
  try {
    const payload = JSON.parse(message.toString());
    console.log(`[${new Date().toISOString()}] Topic: ${topic}`);
    console.log(payload);
  } catch (err) {
    console.warn('Non-JSON message received:', message.toString());
  }
});

client.on('error', (err) => console.error('MQTT connection error:', err.message));
client.on('close', () => console.warn('MQTT connection closed. Retrying...'));
