-- Bazénové čerpadlo: poslední stav + denní spotřeba pro UI (PostgREST).

create or replace view ems.vw_latest_pool_pump
with (security_invoker = false)
as
select
  pp.site_id,
  pp.id                   as pump_id,
  pp.code                 as pump_code,
  pp.rated_power_w,
  pp.schedulable,
  t.measured_at,
  t.is_on,
  t.power_w,
  t.energy_wh_total,
  now() - t.measured_at   as data_age
from ems.asset_pool_pump pp
left join lateral (
  select tp.measured_at, tp.is_on, tp.power_w, tp.energy_wh_total
  from ems.telemetry_pool_pump tp
  where tp.pump_id = pp.id
  order by tp.measured_at desc
  limit 1
) t on true;

comment on view ems.vw_latest_pool_pump is
'Poslední telemetrie bazénového čerpadla (LATERAL per pump). Dashboard karta.';

-- Denní spotřeba z čítače Shelly (delta max−min za pražský den, posledních 8 dní).
create or replace view ems.vw_pool_pump_day_energy
with (security_invoker = false)
as
select
  tp.site_id,
  tp.pump_id,
  (tp.measured_at at time zone 'Europe/Prague')::date as day,
  round((max(tp.energy_wh_total) - min(tp.energy_wh_total)) / 1000.0, 2) as kwh,
  sum(case when tp.is_on then 1 else 0 end) as on_minutes
from ems.telemetry_pool_pump tp
where tp.measured_at >= now() - interval '8 days'
group by 1, 2, 3;

comment on view ems.vw_pool_pump_day_energy is
'Denní kWh čerpadla (delta čítače energy_wh_total) a minuty běhu, 8 dní zpět.
on_minutes = počet ON řádků: drží invariant idle-skip telemetrie (zapnuté
čerpadlo se ukládá každou minutu, vypnuté jen změna/heartbeat).';

grant select on ems.vw_latest_pool_pump to ems_anon;
grant select on ems.vw_pool_pump_day_energy to ems_anon;
