module PayoutEntities
  class Activation < PayoutEntities::Base
    attributes :channel_id, :channel_name, :contract_url,
               :contract_start_date, :contract_end_date, :contract_auto_renew,
               :contract_auto_renew_notice, :contract_renewal_term,
               :subs_enabled, :bits_enabled,
               :pre_roll_ads_enabled, :post_roll_ads_enabled

    self.primary_attribute = :channel_id

    validates :contract_url, :contract_start_date, :contract_end_date,
              :contract_auto_renew_notice, :contract_renewal_term, presence: true

    DEFAULT_CONTRACT_AUTO_RENEW_NOTICE = 90
    DEFAULT_CONTRACT_RENEWAL_TERM = 365

    def self.find_all(options)
      response = get "/payout/activate/channels", headers: ldap_headers(options)
    end

    def activate(options)
      return false unless valid?

      response = post "/payout/activate/#{channel_id}", body: save_params.to_json, headers: PayoutEntity.ldap_headers(options)

      unless response.success?
        msg = response.body["message"].present? ? response.body["message"] : "Internal server error"
        self.errors.add(:base, msg)

        return false
      end

      response.success?
    end

    def save_params
      {
        contract_url: contract_url,
        contract_start_date: contract_start_date.to_datetime,
        contract_end_date: contract_end_date.to_datetime,
        contract_auto_renew: auto_renew?,
        contract_auto_renew_notice: contract_auto_renew_notice,
        contract_renewal_term: contract_renewal_term,
        features: features
      }
    end

    def auto_renew?
      self.class.booleanize contract_auto_renew
    end

    def features
      {
        subs: self.class.booleanize(subs_enabled),
        bits: self.class.booleanize(bits_enabled),
        pre_roll_ads: self.class.booleanize(pre_roll_ads_enabled),
        post_roll_ads: self.class.booleanize(post_roll_ads_enabled)
      }
    end
  end
end
