create or replace function ems.fn_ev_session_apply_patch(
  p_site_id int,
  p_session_id int,
  p_patch jsonb
)
returns jsonb
language plpgsql
as $fn$
declare
  v_id int;
begin
  if not (p_patch ? 'target_soc_pct') and not (p_patch ? 'target_deadline') then
    return jsonb_build_object('success', false, 'error', 'no_fields');
  end if;

  update ems.ev_session es
  set
    target_soc_pct = case
      when p_patch ? 'target_soc_pct' then
        case
          when p_patch->'target_soc_pct' is null
            or jsonb_typeof(p_patch->'target_soc_pct') = 'null' then null
          else (p_patch->>'target_soc_pct')::double precision
        end
      else es.target_soc_pct
    end,
    target_deadline = case
      when p_patch ? 'target_deadline' then
        case
          when p_patch->'target_deadline' is null
            or jsonb_typeof(p_patch->'target_deadline') = 'null' then null
          else (p_patch->>'target_deadline')::timestamptz
        end
      else es.target_deadline
    end
  where es.id = p_session_id
    and es.site_id = p_site_id
  returning es.id into v_id;

  if v_id is null then
    return jsonb_build_object('success', false, 'session_id', null);
  end if;

  return jsonb_build_object('success', true, 'session_id', v_id);
end;
$fn$;

comment on function ems.fn_ev_session_apply_patch(int, int, jsonb) is
  'PATCH EV session – jen klíče přítomné v JSON (ISO string pro deadline).';
