require 'rails_helper'

RSpec.describe Bits::Type do
  include ServiceHelper

  describe "all" do
    let(:twirp_response) do
      data = Code::Justin::Tv::Commerce::Petozi::GetBitsTypesResp.new
      data.bits_types << Code::Justin::Tv::Commerce::Petozi::BitsType.new(id: "1")
      data.bits_types << Code::Justin::Tv::Commerce::Petozi::BitsType.new(id: "2")
      data.bits_types << Code::Justin::Tv::Commerce::Petozi::BitsType.new(id: "3")
      Twirp::ClientResp.new(data, nil)
    end

    before(:each) do
      expect(described_class.twirp_client).to(receive(:get_bits_types)).and_return(twirp_response)
    end

    it 'retrieves all bits types' do
      types = described_class.all
      expect(types.size).to eq(3)
    end
  end

  describe "find" do
    let(:twirp_response) do
      data = Code::Justin::Tv::Commerce::Petozi::GetBitsTypeResp.new
      data.bits_type = Code::Justin::Tv::Commerce::Petozi::BitsType.new(id: "1")
      Twirp::ClientResp.new(data, nil)
    end

    before(:each) do
      expect(described_class.twirp_client).to(receive(:get_bits_type)).and_return(twirp_response)
    end

    it 'retrieves a bits type by ID' do
      type = described_class.find("1")
      expect(type.id).to eq("1")
    end
  end

  describe "save" do

    let(:type) do
      described_class.new(
        id: "1",
        display_name: "some type",
        is_paid: true,
        is_promotional: false,
        cost_per_bits_usc: 1.4,
        entitlement_source_type: :IN_APP_PURCHASE,
        business_attribution: :EXTENSIONS
      )
    end

    describe "when client succeeds" do
      let(:twirp_response) do
        data = Code::Justin::Tv::Commerce::Petozi::PutBitsTypeResp.new
        Twirp::ClientResp.new(data, nil)
      end
      before(:each) do
        expect(described_class.twirp_client).to(receive(:put_bits_type)).and_return(twirp_response)
      end

      it "returns true if save succeeds" do
        expect(type.save).to eq(true)
      end
    end

    describe "when client fails" do
      let(:twirp_response) do
        Twirp::ClientResp.new(nil, Twirp::Error.new(:internal, "some error", {}))
      end
      before(:each) do
        expect(described_class.twirp_client).to(receive(:put_bits_type)).and_return(twirp_response)
      end

      it "returns false" do
        expect(type.save).to eq(false)
      end
    end
  end

  describe "#entitlent_source_types" do
    it "returns all entitlement source types" do
      expect(described_class.entitlement_source_types.size).to eq(Code::Justin::Tv::Commerce::Petozi::EntitlementSourceType.constants.size)
    end
  end

  describe "#business_attributions" do
    it "returns all business attributions" do
      expect(described_class.business_attributions.size).to eq(Code::Justin::Tv::Commerce::Petozi::BusinessAttribution.constants.size)
    end
  end
end
