require './test/test_helper'

class OfferTest < Minitest::Test

  def get_first_offer
    VCR.use_cassette('offer search') do
      @first_offer = Access::Offer.search(query: 'pizza', member_key: 'API_RUBY_GEM_TEST', per_page: 1).offers.first
    end
  end

  def test_offers_search
    assert_equal Access.config.access_token, ENV['ACCESS_TOKEN']

    VCR.use_cassette('offer search') do
      offers_response = Access::Offer.search(query: 'pizza', member_key: 'API_RUBY_GEM_TEST', per_page: 1)
      first_offer = offers_response.offers.first
      assert offers_response.success
      assert_kind_of Access::OfferResponse, offers_response
      assert_kind_of Access::Link, offers_response.links
      assert_kind_of Access::Info, offers_response.info
      assert_kind_of Array, offers_response.offers
      assert_kind_of Access::Offer, first_offer
      assert_kind_of Access::Category, first_offer.categories.first
      assert_kind_of Access::Store, first_offer.offer_store
      assert_kind_of Access::Location, first_offer.location
       assert_kind_of Access::Geolocation, first_offer.location.geolocation
      assert_kind_of Access::Link, first_offer.links
    end
  end

  def test_offers_find
    get_first_offer
    VCR.use_cassette('offer find') do
      offers_response = Access::Offer.find(@first_offer.offer_key, query: 'pizza', member_key: 'API_RUBY_GEM_TEST')
      first_offer = offers_response.offers.first
      assert offers_response.success
      assert_kind_of Access::OfferResponse, offers_response
      assert_kind_of Access::Offer, first_offer
    end
  end

  def test_offers_extra_methods
    VCR.use_cassette('offer search') do
      offers_response = Access::Offer.search(query: 'pizza', member_key: 'API_RUBY_GEM_TEST', per_page: 1)
      first_offer = offers_response.offers.first
      assert offers_response.success
      # location
      assert_equal first_offer.offer_store.physical_location, first_offer.location
      # store
      assert_equal first_offer.offer_store, first_offer.store
    end
  end

  def test_offers_fail_member_key
    VCR.use_cassette('offer search fail member key') do
      offers_response = Access::Offer.search(query: 'pizza')
      refute offers_response.success
      assert_kind_of Access::OfferResponse, offers_response
      assert_kind_of Access::Error, offers_response.error
      assert_equal 401,  offers_response.error.status_code
      assert_equal "Must include a member_key to see details.",  offers_response.error.message
      assert_equal "Unauthorized",  offers_response.error.status
    end
  end

  def test_offers_fail_no_access_token
    orginal_token = ENV['ACCESS_TOKEN']
    Access.config.access_token = ENV['ACCESS_TOKEN'] = nil
    assert_raises(Access::Error::NoAccessToken) { Access::Offer.search(query: 'pizza', member_key: 'API_RUBY_GEM_TEST') }
    Access.config.access_token = ENV['ACCESS_TOKEN'] = orginal_token
  end
end