require 'rails_helper'

module Bits
  describe Badge do
    include ServiceHelper

    let(:user_id) { 123 }
    let(:expected_url) { "/authed/admin/badges/#{user_id}/tiers" }

    describe "#all" do
      let(:success_resp) do
        Faraday::Response.new.tap do |response|
          allow(response).to receive(:success?).and_return(true)
          allow(response).to receive(:status).and_return(200)
          allow(response).to receive(:body).and_return(
            {
              "tiers" => [
                "threshold" => 100,
                "title" => "cheer 100",
                "image_url_1x" => "some_url_1x",
                "image_url_2x" => "some_url_2x",
                "image_url_4x" => "some_url_4x"
              ]
            }
          )
        end
      end

      it 'load the users badges' do
        allow(Bits::Base).to(receive(:get)).with(expected_url).and_return(success_resp)

        badges = Bits::Badge.all(user_id)
        expect(badges.size).to eql(1)
      end
    end

    describe '#update_badge_tiers' do
      let(:success_resp) do
        Faraday::Response.new.tap do |response|
          allow(response).to receive(:success?).and_return(true)
          allow(response).to receive(:status).and_return(200)
        end
      end
      let(:fail_resp) do
        Faraday::Response.new.tap do |response|
          allow(response).to receive(:success?).and_return(false)
          allow(response).to receive(:status).and_return(500)
        end
      end

      let(:tiers) do
        [
          {
            threshold: 100,
            enabled: true,
          },
          {
            threshold: 1000,
            delete_image: true,
          },
          {
            threshold: 2000,
            delete_title: true,
          },
          {
            threshold: 5000,
            enabled: false,
          }
        ]
      end

      it 'returns true if the service call succeeded' do
        allow(Bits::Base).to(receive(:patch).with(expected_url, { body: JSON.dump({ tiers: tiers }) })
                                            .and_return(success_resp))

        expect(Badge.update_badge_tiers(user_id, tiers)).to eql(true)
      end

      it 'returns false if the service call failed' do
        allow(Bits::Base).to(receive(:patch).with(expected_url, { body: JSON.dump({ tiers: tiers }) })
                                            .and_return(fail_resp))

        expect(Badge.update_badge_tiers(user_id, tiers)).to eql(false)
      end
    end
  end
end
