-- map register -> value_verified z modbus_command (poslední verified řádek per register)
-- Od 2026-06-11 generické přes p_asset_type (inverter / ev_charger / …);
-- starou 2-arg signaturu dropnout (default by způsobil ambiguitu).

drop function if exists ems.fn_modbus_last_verified_map(int, int);

create or replace function ems.fn_modbus_last_verified_map(
  p_site_id int,
  p_asset_id int,
  p_asset_type text default 'inverter'
)
returns jsonb
language sql
stable
as $fn$
  select coalesce(
    jsonb_object_agg(register::text, to_jsonb(value_verified)),
    '{}'::jsonb
  )
  from (
    select
      v.register,
      v.value_verified
    from ems.vw_modbus_last_verified v
    where v.site_id = p_site_id
      and v.asset_type = p_asset_type
      and v.asset_id = p_asset_id
  ) t;
$fn$;

comment on function ems.fn_modbus_last_verified_map is
'Mapa register -> poslední verified hodnota z modbus_command pro dané zařízení (site, asset_type, asset_id). Slouží k drop-unchanged v control exporteru.';
