-- Store timer with atomic operations and TTL management
-- KEYS[1]: Timer key (e.g., "auction_timer:12345")
-- KEYS[2]: Timer index key (e.g., "timer_index")
-- KEYS[3]: Timer stats key (e.g., "timer_stats")
-- ARGV[1]: Timer data (JSON serialized)
-- ARGV[2]: TTL in seconds
-- ARGV[3]: Current timestamp
-- ARGV[4]: Timer priority tier (1=memory, 2=redis, 3=database)

local timer_key = KEYS[1]
local index_key = KEYS[2]
local stats_key = KEYS[3]

local timer_data = ARGV[1]
local ttl = tonumber(ARGV[2])
local timestamp = tonumber(ARGV[3])
local tier = tonumber(ARGV[4])

-- Store the timer data with TTL
redis.call('SETEX', timer_key, ttl, timer_data)

-- Add to sorted set index (sorted by expiration time)
local expire_time = timestamp + ttl
redis.call('ZADD', index_key, expire_time, timer_key)

-- Update statistics atomically
local stats = redis.call('HMGET', stats_key, 'total_timers', 'active_timers', 'tier_' .. tier .. '_count')
local total_timers = tonumber(stats[1]) or 0
local active_timers = tonumber(stats[2]) or 0
local tier_count = tonumber(stats[3]) or 0

redis.call('HMSET', stats_key,
    'total_timers', total_timers + 1,
    'active_timers', active_timers + 1,
    'tier_' .. tier .. '_count', tier_count + 1,
    'last_update', timestamp
)

-- Publish notification for new timer
redis.call('PUBLISH', 'timer_events', 
    string.format('{"event":"timer_created","key":"%s","tier":%d,"timestamp":%d}', 
                  timer_key, tier, timestamp))

return 'OK'