require 'spec_helper'

describe TeacherPaymentCharge, no_transaction: true do

  let(:user) { FactoryGirl.create(:user) }
  let(:user2) { FactoryGirl.create(:user) }
  let(:teacher1_auth) { UserAuthorization.create(provider: 'stripe_connect', uid: stripe_account1_id, token: 'abc', refresh_token: 'abc', token_expiration: Date.today + 365, secret: 'secret') }
  let(:teacher2_auth) { UserAuthorization.create(provider: 'stripe_connect', uid: stripe_account2_id, token: 'abc', refresh_token: 'abc', token_expiration: Date.today + 365, secret: 'secret') }
  let(:teacher) { FactoryGirl.create(:user) }
  let(:teacher2) { FactoryGirl.create(:user) }
  let(:teacher_obj) { FactoryGirl.create(:teacher, user: teacher) }
  let(:teacher_obj2) { FactoryGirl.create(:teacher, user: teacher2) }

  let(:lesson) { normal_lesson(user, teacher, finish: true, accept: true, student_show: true, no_after_logic: true) }

  describe "error behavior" do

    before(:each) do
      pending "Lessons put on pause"
      teacher_obj.touch
      teacher_obj2.touch
      teacher.teacher.stripe_account_id = stripe_account1_id
      teacher2.teacher.stripe_account_id = stripe_account2_id
    end

    it "fails after stripe communication (in transaction)" do
      LessonPaymentCharge.transaction do

        Sale.stub(:post_sale_test_failure).and_raise('bad logic after stripe call')

        lesson.analyse

        LessonPaymentCharge.count.should eql 1

        charge = LessonPaymentCharge.first
        charge.billing_attempts.should eql 1
        charge.billed.should be_true
        charge.billing_error_reason.should eql 'bad logic after stripe call'

        Sale.count.should eql 0
      end
    end

    it "fails after stripe communication (no transaction)" do

      Sale.stub(:post_sale_test_failure).and_raise('bad logic after stripe call')

      lesson.analyse

      LessonPaymentCharge.count.should eql 1

      charge = LessonPaymentCharge.first
      charge.billing_attempts.should eql 1
      charge.billed.should be_true
      charge.billing_error_reason.should eql 'bad logic after stripe call'

      Sale.count.should eql 0
    end
  end
end
