-- Update timer atomically with optimistic locking
-- KEYS[1]: Timer key
-- KEYS[2]: Timer stats key
-- ARGV[1]: Expected version (for optimistic locking)
-- ARGV[2]: New timer data (JSON)
-- ARGV[3]: New TTL
-- ARGV[4]: Current timestamp

local timer_key = KEYS[1]
local stats_key = KEYS[2]
local expected_version = ARGV[1]
local new_data = ARGV[2]
local new_ttl = tonumber(ARGV[3])
local timestamp = tonumber(ARGV[4])

-- Get current timer data
local current_data = redis.call('GET', timer_key)
if not current_data then
    return {err = 'TIMER_NOT_FOUND'}
end

-- Parse current data to check version (assumes JSON with version field)
-- For simplicity, we'll use a hash-based approach for version checking
local current_hash = redis.sha1hex(current_data)
if expected_version ~= '' and expected_version ~= current_hash then
    return {err = 'VERSION_MISMATCH'}
end

-- Update timer data with new TTL
redis.call('SETEX', timer_key, new_ttl, new_data)

-- Update statistics
redis.call('HINCRBY', stats_key, 'update_count', 1)
redis.call('HSET', stats_key, 'last_update', timestamp)

-- Publish update notification
redis.call('PUBLISH', 'timer_events', 
    string.format('{"event":"timer_updated","key":"%s","timestamp":%d}', 
                  timer_key, timestamp))

-- Return new version hash
return {ok = redis.sha1hex(new_data)}