require 'test_helper'

class ContractTest < ActiveSupport::TestCase

  disable_transactional_fixtures!

  def test_plan_changed_is_notified_after_commit
    plan = Factory(:account_plan, :issuer => Factory(:simple_account))
    contract = Factory(:contract, :plan => plan)

    other_plan = Factory(:account_plan, :issuer => Factory(:simple_account))

    Contract.transaction do
      contract.change_plan!(other_plan)

      contract.expects(:notify_observers).with(:plan_changed).once
      contract.expects(:notify_observers).with(:bill_variable_for_plan_changed, kind_of(Plan)).once
    end

    # testing that it is not notified again
    contract.save!
  end

  def test_plan_changed_is_notified_just_once
    plan = Factory(:account_plan, :issuer => Factory(:simple_account))
    contract = Factory(:contract, :plan => plan)

    ## explicit transaction
    other_plan = Factory(:account_plan, :issuer => Factory(:simple_account))

    contract.expects(:notify_observers).with(:plan_changed).once

    contract.expects(:notify_observers).with(:bill_variable_for_plan_changed, kind_of(Plan)).once

    Contract.transaction do
      contract.change_plan!(other_plan)
    end

    ## just save
    other_contract = Factory(:contract, :plan => plan)

    other_contract.expects(:notify_observers).with(:plan_changed).once
    other_contract.expects(:notify_observers).with(:bill_variable_for_plan_changed, kind_of(Plan)).once

    other_contract.change_plan!(other_plan)
  end

  context '#paid?' do
    setup do
      buyer = Factory :buyer_account
      service = buyer.provider_account.first_service!
      #making the service subscribeable
      service.publish!
      @plan = service.service_plans.first

      @contract = buyer.buy! @plan
    end

    should 'be delegated to plan' do
      assert !@plan.paid?
      assert !@contract.paid?
      @plan.update_attribute :cost_per_month, 10.0

      @plan.reload
      @contract.reload

      assert @plan.paid?
      assert @contract.paid?
    end
  end #paid?


  def test_bill_for
    invoice = FactoryGirl.create(:invoice)
    month = Month.new(Time.now)

    contract = FactoryGirl.create(:simple_cinstance, paid_until: 1.day.ago)

    contract.bill_for(month, invoice)

    assert_equal month.end.to_time.end_of_day, contract.paid_until
  end
end
