-- Migration 023: Proxy node improvements
-- Adds heartbeat_count for uptime computation
-- Adds unique index on (ip, port) for deduplication

-- Track actual heartbeats received so we can compute uptime_pct accurately
ALTER TABLE proxy_nodes
  ADD COLUMN IF NOT EXISTS heartbeat_count INTEGER NOT NULL DEFAULT 0;

-- Unique index on ip+port so we can deduplicate registrations from same machine
-- NOTE: partial index — only enforces uniqueness when ip IS NOT NULL
CREATE UNIQUE INDEX IF NOT EXISTS idx_proxy_nodes_ip_port
  ON proxy_nodes (ip, port)
  WHERE ip IS NOT NULL;

-- Backfill: estimate heartbeat_count from registered_at + 30s interval
-- Assumes ~95% uptime for existing nodes that are currently online
UPDATE proxy_nodes
SET heartbeat_count = GREATEST(1,
    FLOOR(EXTRACT(EPOCH FROM (NOW() - registered_at)) / 30)::INTEGER
  )
WHERE status = 'online' AND heartbeat_count = 0;
