class Finance::InvoiceProxy

  attr_reader :provider, :buyer, :month
  delegate :line_items, :to => :invoice

  def initialize(provider, buyer, month)
    @provider = provider
    @buyer = buyer
    @month = month
    @used = false
  end

  def bill(*args, &block)
    return unless should_bill?

    @used = true
    invoice.bill(*args, &block)
  end

  # Returns true if it was actually used to bill something.
  def used?
    @used
  end

  private

  def should_bill?
    @buyer.billing_monthly?
  end

  # TODO: handle mutliple invoices for one month
  #
  def invoice
    @invoice ||= Invoice.by_month(@month.to_param).opened_by_buyer(@buyer)

    unless @invoice
      @invoice = @provider.billing_strategy.create_invoice!( :buyer_account => @buyer, :period => @month)
    end

    @invoice
  end

end
