create or replace function ems.fn_inverter_modbus_caps_patch(
  p_site_id int,
  p_inverter_id int,
  p_patch jsonb
)
returns jsonb
language plpgsql
as $fn$
declare
  v_charge int;
  v_discharge int;
  r record;
begin
  if not (p_patch ? 'deye_register_max_charge_a')
     and not (p_patch ? 'deye_register_max_discharge_a') then
    return jsonb_build_object('ok', false, 'error', 'no_fields');
  end if;

  v_charge := case
    when p_patch ? 'deye_register_max_charge_a' then
      case
        when p_patch->'deye_register_max_charge_a' is null
          or jsonb_typeof(p_patch->'deye_register_max_charge_a') = 'null' then null
        else (p_patch->>'deye_register_max_charge_a')::int
      end
    else null
  end;

  v_discharge := case
    when p_patch ? 'deye_register_max_discharge_a' then
      case
        when p_patch->'deye_register_max_discharge_a' is null
          or jsonb_typeof(p_patch->'deye_register_max_discharge_a') = 'null' then null
        else (p_patch->>'deye_register_max_discharge_a')::int
      end
    else null
  end;

  update ems.asset_inverter ai
  set
    deye_register_max_charge_a = case
      when p_patch ? 'deye_register_max_charge_a' then v_charge
      else ai.deye_register_max_charge_a
    end,
    deye_register_max_discharge_a = case
      when p_patch ? 'deye_register_max_discharge_a' then v_discharge
      else ai.deye_register_max_discharge_a
    end
  where ai.id = p_inverter_id
    and ai.site_id = p_site_id
  returning ai.id, ai.code, ai.deye_register_max_charge_a, ai.deye_register_max_discharge_a
  into r;

  if r.id is null then
    return jsonb_build_object('ok', false, 'error', 'not_found');
  end if;

  return jsonb_build_object(
    'ok', true,
    'inverter_id', r.id,
    'code', r.code,
    'deye_register_max_charge_a', r.deye_register_max_charge_a,
    'deye_register_max_discharge_a', r.deye_register_max_discharge_a
  );
end;
$fn$;

comment on function ems.fn_inverter_modbus_caps_patch(int, int, jsonb) is
  'PATCH stropů proudu reg 108/109 – explicitní JSON null maže strop.';
