module Reports
  module NetSuite
    class DonorExport
      include CsvExport

      FIELDS = %w[id name email createdDate attention addr_1 addr_2 city state zip externalId externalType].freeze

      def initialize(session)
        @session = session
        filter = Reports::Filter.new(@session)
        records = Donor.active.order(:id)
        @donors = filter.apply_date_filter(records, :created_at)
      end

      def records_present?
        @donors.exists?
      end

      def each
        @donors.each do |donor|
          yield Row.new(donor)
        end
      end

      class Row
        attr_reader :donor, :attention, :addr_1, :addr_2, :city, :state, :zip

        delegate :name, :email, :external_id, :external_type, to: :donor

        def initialize(donor)
          @donor = donor
          extract_address
        end

        def id
          "Donor-#{donor.id}"
        end

        def created_date
          donor.created_at.strftime("%m/%d/%Y")
        end

        private

        def extract_address
          result = AddressParser.new.parse(donor.primary_address)
          @attention = result[:attention]
          @addr_1 = result[:address1]
          @addr_2 = result[:address2]
          @city = result[:city]
          @state = result[:state]
          @zip = result[:zip]
        end
      end
    end
  end
end
