-- Denní cíl filtrace bazénu: dle teploty vody (poslední měření < 24 h),
-- jinak fallback daily_runtime_min. Vstup pro solver (pool_on[t] budget).

create or replace function ems.fn_pool_daily_runtime_min(p_pump_id int)
returns jsonb
language sql
stable
as $fn$
  select jsonb_build_object(
    'runtime_min',
    coalesce(
      case
        when t.value is not null then
          least(
            pp.runtime_max_min,
            greatest(
              pp.runtime_min_min,
              round(
                pp.runtime_base_min
                + pp.runtime_min_per_c * greatest(0, t.value - pp.runtime_ref_temp_c)
              )::int
            )
          )
      end,
      pp.daily_runtime_min
    ),
    'water_temp_c', t.value,
    'temp_measured_at', t.measured_at,
    'source', case when t.value is not null then 'temp_function' else 'static' end,
    'schedulable', pp.schedulable
  )
  from ems.asset_pool_pump pp
  left join lateral (
    select ts.value, ts.measured_at
    from ems.telemetry_loxone_sensor ts
    where ts.sensor_id = pp.water_temp_sensor_id
      and ts.measured_at > now() - interval '24 hours'
    order by ts.measured_at desc
    limit 1
  ) t on true
  where pp.id = p_pump_id;
$fn$;

comment on function ems.fn_pool_daily_runtime_min is
'Cíl minut filtrace/den: clamp(base + per_c×(teplota−ref), min, max) z poslední teploty vody (<24 h), jinak daily_runtime_min. JSON s detailem pro UI/solver.';
