// Writes to state.rooms.<roomKey>. Room from Zigbee device via global roomConfig.deviceToRoom. See /root/.node-red/room-config.js.
const actionToSwitch = { single: 1, double: 2, hold: 3, release: 4, triple: 5, quad: 6 };
const config = global.get('roomConfig');
const deviceToRoom = (config && config.deviceToRoom) ? config.deviceToRoom : { 'Office Switch': 'cmd_livingroom' };
const friendlyName = (msg.payload && msg.payload.friendly_name) ? msg.payload.friendly_name : '';
const ROOM_NAME = deviceToRoom[friendlyName] || 'cmd_livingroom';
const payload = msg.payload || {};
const actionRaw = (payload.action || payload.click || '').toLowerCase();
// Support "1_single", "2_double" etc. (button_number + action) or plain "single", "double"
const parts = actionRaw.split('_');
let swIndex = null;
if (parts.length >= 2) {
  const buttonNum = parseInt(parts[0], 10);
  if (buttonNum >= 1 && buttonNum <= 6) swIndex = buttonNum;
}
if (swIndex == null) swIndex = actionToSwitch[actionRaw];
if (swIndex == null && parts.length >= 2) swIndex = actionToSwitch[parts.slice(1).join('_')];
if (swIndex == null) swIndex = actionToSwitch[parts[parts.length - 1]];

if (swIndex == null) {
  node.warn('[Zigbee to NVL] unknown action: ' + JSON.stringify(actionRaw) + ' payload=' + JSON.stringify(payload));
  return null;
}

if (!flow.get('nvlInState')) flow.set('nvlInState', { rooms: {}, boiler: {} });
const state = flow.get('nvlInState');
if (!state.rooms[ROOM_NAME]) state.rooms[ROOM_NAME] = {};
state.rooms[ROOM_NAME]['zigbee_sw' + swIndex] = true;
flow.set('nvlInState', state);

node.warn('[Zigbee to NVL] ' + ROOM_NAME + ' zigbee_sw' + swIndex + '=true (action=' + actionRaw + '), buildAndSend + zigbeeClear');

msg.payload = { buildAndSend: true };
msg.zigbeeClear = { room: ROOM_NAME, key: 'zigbee_sw' + swIndex };
return msg;
