
class BillingObserver < ActiveRecord::Observer

  class RangeForVariableCost < Range; end
  observe :contract

  # It is called 'manually' from Contract#notify_plan_changed

  def bill_variable_for_plan_changed(contract, plan)
    if contract.provider_account.provider_can_use?(:instant_bill_plan_change)
      current_invoice = Finance::InvoiceProxy.new(contract.provider_account,
                                                  contract.account,
                                                  Month.new(Time.now))

      period_from = contract.variable_cost_paid_until
      last_midnight = Date.today.beginning_of_day
      period = RangeForVariableCost.new(period_from, last_midnight)

      contract.bill_for_variable(period, current_invoice, plan)
    end
  end



  def plan_changed(contract)
    now = Time.now.utc

    # HACK: START

    return if contract.buyer_account.provider_account.nil?
    strategy = contract.buyer_account.provider_account.billing_strategy
    return unless strategy
    # HACK: END

    # TODO: add 'now' parameter
    return if contract.trial?

    from = [ contract.paid_until, now.beginning_of_month ].max
    before = TimeRange.new(from, now)
    after = TimeRange.new(now, now.end_of_month)

    strategy.bill_plan_change(contract, after)
    # move this line inside the billing strategy
    contract.update_attribute :paid_until, now.end_of_month
  end

end
