def events
  EventStore::Repository.adapter
end

And(/^there are no events$/) do
  events.delete_all
end

And(/^there should be (\d+) application cancelled event$/) do |n|
  cancelled = events.where(event_type: Cinstances::CinstanceCancellationEvent)

  assert_equal n.to_i, cancelled.count
end

And(/^there should be (\d+) valid service contract cancelled event$/) do |count|
  check_events_validity!(ServiceContracts::ServiceContractCancellationEvent, count)
end

And(/^there should be (\d+) valid service contract created event$/) do |count|
  check_events_validity!(ServiceContracts::ServiceContractCreatedEvent, count)
end

And(/^there should be (\d+) valid account created event$/) do |count|
  check_events_validity!(Accounts::AccountCreatedEvent, count)
end

And(/^there should be (\d+) valid account deleted event$/) do |count|
  check_events_validity!(Accounts::AccountDeletedEvent, count)
end

And(/^there should be (\d+) valid application created event$/) do |count|
  check_events_validity!(Applications::ApplicationCreatedEvent, count)
end

And(/^there should be (\d+) valid cinstance cancellation event$/) do |count|
  check_events_validity!(Cinstances::CinstanceCancellationEvent, count)
end

And(/^all the events should be valid$/) do
  assert events.all.all? { |event| event.attributes && event.valid? }, 'all the events are not valid'
end

def check_events_validity!(type, expected_count)
  specific_events = events.where(event_type: type)

  specific_events.each do |event|
    event_entity = EventStore::Repository.build_entity(event)

    event_entity.data.each do |key, value|
      assert value.present?, "#{key} is blank"
    end
  end

  assert_equal expected_count.to_i, specific_events.count
end
