# frozen_string_literal: true

$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'sensu/extension/tueor'

require 'minitest/autorun'
require 'eventmachine'
require 'sensu/logger'
require 'sensu/settings'
require 'securerandom'

# Helpers for running tests
module TestHelpers
  def schedule(method = nil, after: 0, &block)
    raise 'Schedule called without a method or a block' if method.nil? && block.nil?
    block ||= proc { __send__ method.to_sym }

    if after.positive?
      EventMachine.add_timer(after, &block)
    else
      EventMachine.schedule(&block)
    end
  end

  def run_extension(extension, data:, timeout: 10)
    EventMachine.run do
      extension = extension.new if extension.is_a? Class
      schedule(after: timeout) { raise "Test timed out after #{timeout} seconds..." }
      schedule do
        extension.safe_run(data) do |output, status|
          yield output, status, extension if block_given?
          EventMachine.stop
        end
      end
    end
  end

  def logger
    Sensu::Logger.get(log_level: :fatal)
  end

  def settings
    Sensu::Settings.get
  end

  def epoch
    Time.now.to_i
  end

  def client_template
    {
      name: 'i-424242',
      address: '127.0.0.1',
      subscriptions: [
        'test'
      ],
      timestamp: epoch
    }
  end

  def check_template
    {
      name: 'test',
      type: 'standard',
      issued: epoch,
      command: 'echo WARNING && exit 1',
      subscribers: [
        'test'
      ],
      interval: 1,
      output: 'WARNING',
      status: 1,
      executed: epoch,
      history: [0, 1]
    }
  end

  def event_template
    one_second_ago = epoch - 1
    {
      id: ::SecureRandom.uuid,
      client: client_template,
      check: check_template,
      last_ok: one_second_ago,
      last_state_change: one_second_ago,
      occurrences: 1,
      occurrences_watermark: 1,
      action: :create
    }
  end
end
