class Payments::Payjunction::SyncAccountsService < ApplicationService
  include Payments::Payjunction::Httpable

  def initialize(school)
    @school = school
  end

  def call
    path = '/terminals'
    data = request('Get', path, @school)
    return unless data['results']

    add_accounts(data['results'])
  end

  private
    def add_accounts(data)
      data.each do |account|
        next unless account['enabled']

        payment_type = case account['type']
        when 'CARD'
          :credit_card
        when 'ACH'
          :ach
        end

        payjunction_account = @school.payjunction_accounts
          .find_or_initialize_by(account_id: account['terminalId'])
        payjunction_account.name = account['nickName']
        payjunction_account.payment_type = payment_type if payjunction_account.new_record?
        payjunction_account.save
      end
    end
end
