-- poslední úspěšně ověřený zápis per (site, asset, register)

drop view if exists ems.vw_modbus_last_verified;

create view ems.vw_modbus_last_verified as
select distinct on (mc.site_id, mc.asset_type, mc.asset_id, mc.register)
  mc.id,
  mc.site_id,
  mc.asset_type,
  mc.asset_id,
  mc.register,
  mc.value_verified,
  mc.verified_at,
  mc.status
from ems.modbus_command mc
where mc.status = 'verified'
  and mc.value_verified is not null
order by mc.site_id, mc.asset_type, mc.asset_id, mc.register, mc.verified_at desc nulls last, mc.id desc;

comment on view ems.vw_modbus_last_verified is
  'DISTINCT ON (register) poslední verified řádek pro ověření / mapu registrů.';
