require 'rails_helper'

module Substwirp
  describe Subscription do
    include ServiceHelper

    describe 'access_start' do
      let(:benefit_start) { Time.now }
      let(:subscription) { Subscription.new(benefit_start: benefit_start) }
      subject { subscription.access_start }

      it { is_expected.to be(benefit_start) }
    end

    describe 'access_end' do
      let(:benefit_end) { Time.now }
      let(:subscription) { Subscription.new(benefit_end: benefit_end) }
      subject { subscription.access_end }

      it { is_expected.to be(benefit_end) }
    end

    describe 'get_by_purchase_profile' do
      let(:id) { "1234" }
      let(:product_id) { "567" }
      let(:owner_id) { "890" }
      let(:benefit_start) { Time.now }
      let(:benefit_end) { Time.now }
      let(:channel_id) { "12341234" }
      let(:is_renewable) { true }
      let(:purchase_profile_id) { "1" }

      let(:subscription) do
        {
          "id" => id,
          "product_id" => product_id,
          "owner_id" => owner_id,
          "benefit_start" => benefit_start,
          "benefit_end" => benefit_end,
          "origin_id" => purchase_profile_id,
          "channel_id" => channel_id,
          "is_renewable" => is_renewable,
        }
      end

      let(:subscription_data) do
        double(
          subscriptions: [subscription]
        )
      end

      let(:get_tickets_by_origin_i_ds_response) do
        double(
          error: error,
          data: subscription_data
        )
      end

      subject { Subscription.get_by_purchase_profile(purchase_profile_id) }

      context 'with successful subscriptions response' do
        let(:error) { nil }

        it 'should call twirp_client get_tickets_by_origin_i_ds and returns subscriptions object' do
          expect_any_instance_of(::Code::Justin::Tv::Revenue::Subscriptions::SubscriptionsClient).to receive(:get_tickets_by_origin_i_ds).with({:origin_ids => [purchase_profile_id]}).and_return(get_tickets_by_origin_i_ds_response)
          expect(subject).to have_attributes(
            :id => id,
            :product_id => product_id,
            :owner_id => owner_id,
            :benefit_start => benefit_start,
            :benefit_end => benefit_end,
            :channel_id => channel_id,
            :is_renewable => is_renewable,
            :origin_id => purchase_profile_id
          )
        end
      end

      context 'with error subscriptions response' do
        let(:error) { double(msg: 'failed something') }

        it 'should return nil' do
          expect_any_instance_of(::Code::Justin::Tv::Revenue::Subscriptions::SubscriptionsClient).to receive(:get_tickets_by_origin_i_ds).with({:origin_ids => [purchase_profile_id]}).and_return(get_tickets_by_origin_i_ds_response)
          expect(subject).to be(nil)
        end
      end
    end
  end
end