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

  def initialize(school, action, options={})
    @school = school
    @contacts = options[:family]&.contacts
    @external_id = options[:external_id]
    @action = action
    @path = '/customers'
  end

  def call
    return unless @school.payjunction_credential

    case @action
    when :create
      @contacts.each do |contact|
        next if contact.payjunction_contact

        options = {
          custom1: 'Contact',
          identifier: contact.id,
          email: contact.email,
          firstName: contact.first_name,
          lastName: contact.last_name,
          phone: contact.home_phone,
          phone2: contact.cell_phone
        }
        data = request('Post', @path, @school, options)
        account = contact.build_payjunction_contact
        account.external_id = data['customerId']
        account.save!
      end
    when :show
      @path += "/#{@external_id}"
      request('Get', @path, @school)
    end
  end
end
