// Run this AFTER nvl-receive. Syncs all mapped lights from PLC state to HA entities.
// Map comes from global roomConfig (single source of truth). See /root/.node-red/room-config.js.
// Connect output 1 → Action node (turn_on), output 2 → Action node (turn_off).

const config = global.get('roomConfig');
const LIGHT_ENTITY_MAP = (config && config.lightEntityMap && config.lightEntityMap.length) ? config.lightEntityMap : [
  { room: 'light_livingRoom', light: 1, entityId: 'input_boolean.living_room_new' },
];

const payload = msg.payload || {};
const onMsgs = [];
const offMsgs = [];

for (const entry of LIGHT_ENTITY_MAP) {
  const room = payload[entry.room] || {};
  const isOn = !!(room['l_' + entry.light] || room['l' + entry.light]);

  const flowKey = 'nvlToHa_' + entry.entityId.replace(/\./g, '_');
  const last = flow.get(flowKey);
  if (last === isOn) continue;
  flow.set(flowKey, isOn);

  const domain = entry.entityId.split('.')[0] || 'input_boolean';
  const action = domain + '.' + (isOn ? 'turn_on' : 'turn_off');
  const out = { payload: { action: action, target: { entity_id: [entry.entityId] } } };
  if (isOn) onMsgs.push(out); else offMsgs.push(out);
}

if (onMsgs.length === 0 && offMsgs.length === 0) return null;
return [onMsgs, offMsgs];
