// Use when you don't use the Action node: prepares one msg for the "http request" node to call HA.
// Accepts either: (1) Action format: payload.action + payload.target.entity_id, or (2) payload.entity_id + msg.service.
// Set ha_base_url and ha_token in flow or env.

const HA_BASE_URL = flow.get('ha_base_url') || 'http://homeassistant.local:8123';
const HA_TOKEN = flow.get('ha_token') || env.get('HA_TOKEN') || '';

const p = msg.payload || {};
let entityId = p.target && p.target.entity_id && p.target.entity_id[0];
let domain = 'input_boolean';
let service = 'turn_off';
if (p.action) {
  const parts = p.action.split('.');
  domain = parts[0];
  service = parts[1] || 'turn_off';
}
if (!entityId) entityId = p.entity_id;
if (!entityId) return null;
if (!p.action) domain = (entityId + '').split('.')[0];

const url = HA_BASE_URL.replace(/\/$/, '') + '/api/services/' + domain + '/' + service;

msg.url = url;
msg.method = 'POST';
msg.headers = {
  'Authorization': 'Bearer ' + HA_TOKEN,
  'Content-Type': 'application/json'
};
msg.payload = { entity_id: entityId };
return msg;
