// Build the payload for nvl-send from flow.nvlInState.
// Room list comes from global roomConfig (single source of truth). See /root/.node-red/room-config.js.
// Wire: HA to NVL / Zigbee to NVL → this function → nvl-send → udp out

const struct_room_cmds_default = {
  ha_l1_on: false, ha_l1_off: false, ha_l2_on: false, ha_l2_off: false,
  ha_l3_on: false, ha_l3_off: false, ha_l4_on: false, ha_l4_off: false,
  ha_l5_on: false, ha_l5_off: false, ha_l6_on: false, ha_l6_off: false,
  zigbee_sw1: false, zigbee_sw2: false, zigbee_sw3: false,
  zigbee_sw4: false, zigbee_sw5: false, zigbee_sw6: false,
  ha_all_on: false, ha_all_off: false
};

const config = global.get('roomConfig');
const roomNames = (config && config.roomNames && config.roomNames.length) ? config.roomNames : ['cmd_livingroom'];

const state = flow.get('nvlInState') || { rooms: {}, boiler: {} };
const rooms = state.rooms || {};
const payload = {};

for (const name of roomNames) {
  const cmd = rooms[name] || {};
  payload[name] = { ...struct_room_cmds_default };
  for (const k of Object.keys(struct_room_cmds_default)) {
    if (cmd[k] !== undefined) payload[name][k] = !!cmd[k];
  }
}

msg.payload = payload;
return msg;
