--- Utility functions for Kong o11y-proxy plugin
-- Common utility functions shared across multiple modules

local Utils = {}

--- Parse ISO 8601 timestamp to Unix epoch
-- @param iso8601_time string in format "2023-10-20T12:34:56Z" or "2023-10-20T12:34:56"
-- @return number Unix timestamp or nil on error
-- Note: Timestamps ending with 'Z' are treated as UTC, others as local time
function Utils.parse_iso8601(iso8601_time)
  if not iso8601_time then
    return nil
  end
  
  local pattern = "^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)"
  local year, month, day, hour, min, sec = iso8601_time:match(pattern)
  
  if not year then
    return nil
  end
  
  local ts = os.time({
    year = tonumber(year),
    month = tonumber(month),
    day = tonumber(day),
    hour = tonumber(hour),
    min = tonumber(min),
    sec = tonumber(sec)
  })
  
  -- If timestamp ends with 'Z', it's UTC time
  -- os.time() interprets the time table as local time, so we need to adjust
  if iso8601_time:match("Z%s*$") then
    local utc_date = os.date("!*t", ts)
    local utc_ts_from_local = os.time(utc_date)
    local offset = os.difftime(ts, utc_ts_from_local)
    ts = ts + offset
  end
  
  return ts
end

return Utils
