-- Cap pro reg 340 max solar power (W): plný výkon střídače, ne jen součet Wp polí A.
create or replace function ems.fn_inverter_pv_a_max_w(p_inverter_id int)
returns int
language sql
stable
as $$
  with pv as (
    select coalesce(sum(nominal_power_wp), 0)::int as wp_sum
    from ems.asset_pv_array
    where inverter_id = p_inverter_id
      and controllable = true
  )
  select case
    when (select wp_sum from pv) <= 0 then 0
    else coalesce(
      nullif(ai.deye_reg340_max_solar_w, 0),
      nullif(ai.max_dc_input_w, 0),
      (select wp_sum from pv),
      0
    )::int
  end
  from ems.asset_inverter ai
  where ai.id = p_inverter_id
$$;

comment on function ems.fn_inverter_pv_a_max_w(int) is
  'Cap pro reg 340 (max solar power, W): deye_reg340_max_solar_w, jinak max_dc_input_w, jinak součet Wp řiditelných polí. 0 = bez řiditelného PV A nebo bez capu — EMS reg 340 nezapisuje.';
