-- 20260709-143054 STEP_044M_ACTIVITY_SAMPLER_ONE_SHOT_DB_UPDATE_IMPLEMENT_20260709-143054
-- STEP_044M one-shot activity sampler DB update.
BEGIN;

WITH v(peer_id,tunnel_ip,last_tx_packets,last_tx_bytes,last_rx_packets,last_rx_bytes,active_now,set_last_activity_at,new_state,reason) AS (
VALUES
('376dfa07-0ba4-4182-af39-389a2cb3badd'::uuid,'10.253.1.10/32'::inet,30::bigint,6840::bigint,30::bigint,6840::bigint,true,true,'active'::text,'activity_sampler_active'::text),
('cb533a1a-7070-416d-9272-846327545060'::uuid,'10.253.1.11/32'::inet,0::bigint,0::bigint,0::bigint,0::bigint,false,false,'idle'::text,'activity_sampler_idle_no_delta'::text),
('a3cbe3b5-8416-4847-b5ee-21f42359b465'::uuid,'10.253.1.12/32'::inet,0::bigint,0::bigint,0::bigint,0::bigint,false,false,'idle'::text,'activity_sampler_idle_no_delta'::text),
('219a1f63-ec47-4f72-9663-c1a17d82301e'::uuid,'10.253.1.13/32'::inet,0::bigint,0::bigint,0::bigint,0::bigint,false,false,'idle'::text,'activity_sampler_idle_no_delta'::text),
('e4adcfa1-6fbc-4471-b66b-8d7837f35f9d'::uuid,'10.253.1.14/32'::inet,0::bigint,0::bigint,0::bigint,0::bigint,false,false,'idle'::text,'activity_sampler_idle_no_delta'::text)
),
updated AS (
  UPDATE public.peer_egress_leases AS l
  SET
    last_tx_packets = v.last_tx_packets,
    last_tx_bytes = v.last_tx_bytes,
    last_rx_packets = v.last_rx_packets,
    last_rx_bytes = v.last_rx_bytes,
    state = v.new_state,
    last_activity_at = CASE WHEN v.set_last_activity_at THEN now() ELSE l.last_activity_at END,
    updated_at = now(),
    reason = v.reason
  FROM v
  WHERE l.peer_id = v.peer_id
    AND l.tunnel_ip = v.tunnel_ip
  RETURNING l.peer_id
)
SELECT 'sampler_update_rows', count(*)::text FROM updated;

COMMIT;
