class Tep::FeeService < Tep::ApplicationService
  def initialize(school, applicant, options)
    @school = school
    @applicant = applicant
    @options = options
  end

  def call
    data = JSON.parse(rest_client_request(:post, url, associated, :admissions_fees, body: body))
    data[:link] = /<script.*?src="(.*?)"/.match(data['embed'])[1]
    data.merge(success: true)
  rescue
    { success: false }
  end

  private
    def endpoint
      :fee
    end

    # Determine the associated model for the connection log
    # This is used for the polymorphic association
    # The associated model is the applicant if the fee is for the applicant
    # Otherwise, the associated model is the family
    def associated
      @options[:applicant_fee] ? @applicant : @applicant.family
    end

    def admission_school_year_id
      @school.admission_config.school_year_id
    end

    def fee_id
      # TEP only accepts numbers for fee_id
      # Use arbitary numbers as delimiters to ensure unqiue ids
      return "1#{@applicant.id}2#{@applicant.application_id}" if @options[:applicant_fee]

      "3#{@applicant.family_id}4#{admission_school_year_id}"
    end

    def body
      {
        message_id: SecureRandom.uuid,
        fee_id: fee_id,
        name: @options[:applicant_fee] ? ' New Admission Application Fee' : 'Admission Family Fee',
        amount: @options[:amount].to_f * 100, # amount is in pennies
        student_id: @options[:applicant_fee] ? @applicant.student_id : nil,
        contact_id: @options[:contact_id],
        type: @options[:type]
      }
    end
end
