create or replace function ems.fn_signal_enqueue_bool(
  p_site_id int,
  p_signal_code text,
  p_value boolean
)
returns int
language plpgsql
as $fn$
declare
  v_route record;
  v_value_text text;
  v_count int := 0;
begin
  -- Zařadí bool signál do odchozí fronty pro všechny aktivní routy (site, kód).
  -- Transformaci na text dělá per route stejně jako backend (_bool_to_text):
  -- transform_json->'map_bool'->>'true'/'false', default '1'/'0'.
  for v_route in
    select r.id, r.site_id, r.destination_type, r.destination_key, r.transform_json
    from ems.signal_route r
    where r.site_id = p_site_id
      and r.signal_code = p_signal_code
      and r.enabled = true
  loop
    v_value_text := coalesce(
      v_route.transform_json -> 'map_bool' ->> (case when p_value then 'true' else 'false' end),
      case when p_value then '1' else '0' end
    );

    insert into ems.signal_state (
      site_id, signal_code, destination_type, destination_key,
      last_desired_value_text, updated_at
    )
    values (
      p_site_id, p_signal_code, v_route.destination_type, v_route.destination_key,
      v_value_text, now()
    )
    on conflict (site_id, signal_code, destination_type, destination_key)
    do update set
      last_desired_value_text = excluded.last_desired_value_text,
      updated_at = now();

    insert into ems.signal_outbound_journal (
      route_id, site_id, signal_code, value_text, value_num, status,
      attempt_count, next_attempt_at
    )
    values (
      v_route.id, p_site_id, p_signal_code, v_value_text,
      case when p_value then 1 else 0 end, 'queued', 0, now()
    );

    v_count := v_count + 1;
  end loop;

  return v_count;
end;
$fn$;

comment on function ems.fn_signal_enqueue_bool is
  'Zařadí bool signál (např. POOL_PUMP_ON) do signal_outbound_journal pro všechny aktivní routy daného site a kódu; doručení a verify řeší signal_service (každých 15 s). Vrací počet zařazených řádků. Použití: select ems.fn_signal_enqueue_bool(1, ''POOL_PUMP_ON'', true);';
