create or replace function ems.fn_deye_clock_drift_sec(
  p_device_ts timestamptz,
  p_reference_ts timestamptz
)
returns int
language sql
immutable
as $fn$
  select case
    when p_device_ts is null or p_reference_ts is null then null::int
    else abs(extract(epoch from (p_device_ts - p_reference_ts)))::int
  end;
$fn$;

comment on function ems.fn_deye_clock_drift_sec(timestamptz, timestamptz) is
  'Absolutní odchylka hodin Deye vs referenční UTC (sekundy).';
