module Payments
  class PurchasePayment < Payments::Base
    self.primary_attribute = :id

    attributes :id,
               :purchase_profile_id,
               :ext_transaction_id,
               :state,
               :payment_provider,
               :gross_amount,
               :est_fees,
               :details,
               :created_on,
               :recognized_on,
               :updated_on,
               :received_on

    FILTER_PARAMS = [:id, :purchase_profile_id, :ext_transaction_id, :state, :payment_provider].freeze

    def self.filter(options = {})
      filter_params = options.slice(*FILTER_PARAMS)

      return [] if filter_params.blank?
      response = get '/purchase_payments', params: filter_params

      if response.success?
        response.body['purchase_payments'].map do |purchase_payment|
          from_attributes(purchase_payment)
        end
      else
        []
      end
    end

    def self.find(id)
      return if id.blank?
      response = get "/purchase_payments/#{id}"
      from_attributes(response.body) if response.success?
    end

    def created_on
      DateTime.parse(@created_on) rescue nil
    end

    def recognized_on
      DateTime.parse(@recognized_on) rescue nil
    end

    def updated_on
      DateTime.parse(@updated_on) rescue nil
    end

    def received_on
      DateTime.parse(@received_on) rescue nil
    end
  end
end
