create or replace function ems.fn_modbus_journal_list(p_site_id int, p_limit int)
returns jsonb
language sql
stable
as $fn$
  select coalesce(
    jsonb_agg(
      jsonb_build_object(
        'id', q.id,
        'register', q.register,
        'register_name', q.register_name,
        'value_to_write', q.value_to_write,
        'value_written', q.value_written,
        'value_verified', q.value_verified,
        'status', q.status,
        'attempt_count', q.attempt_count,
        'created_at', q.created_at
      )
      order by q.created_at desc
    ),
    '[]'::jsonb
  )
  from (
    select
      mc.id,
      mc.register,
      mc.register_name,
      mc.value_to_write,
      mc.value_written,
      mc.value_verified,
      mc.status,
      mc.attempt_count,
      mc.created_at
    from ems.modbus_command mc
    where mc.site_id = p_site_id
    order by mc.created_at desc
    limit p_limit
  ) q;
$fn$;

comment on function ems.fn_modbus_journal_list(int, int) is
  'Poslední Modbus příkazy pro site (GET control/journal).';
