module JamRuby
  class AffiliateDistribution < ActiveRecord::Base


    belongs_to :sale_line_item, class_name: 'JamRuby::SaleLineItem'
    belongs_to :affiliate_referral, class_name: 'JamRuby::AffiliatePartner', foreign_key: :affiliate_referral_id

    validates :affiliate_referral, presence:true
    validates :affiliate_referral_fee_in_cents, numericality: {only_integer: false}

    def self.create(affiliate_referral, fee_in_cents, sale_line_item)
      distribution = AffiliateDistribution.new
      distribution.affiliate_referral = affiliate_referral
      distribution.affiliate_referral_fee_in_cents = fee_in_cents
      distribution.sale_line_item = sale_line_item
      distribution
    end

    def self.subscription_plans_count(affiliate_referral_id, start_at, end_at)
      AffiliateDistribution.where(
        affiliate_referral_id: affiliate_referral_id, 
        product_type: 'Subscription').where("
          DATE(affiliate_distributions.created_at) >= ?", start_at).where("
          DATE(affiliate_distributions.created_at) <= ?", end_at).group_by(&:product_code).map do |product_code, distributions|
          { 
            plan: product_code,
            count: distributions.size
          }
        end
    end
  end
end
