class Paya::FormService < Paya::ApplicationService
  def initialize(school, endpoint, options={})
    @endpoint = endpoint
    @family = options[:family]
    @contact = options[:contact]
    @options = options
    @payform = endpoint == :payform
    @subtotal = options[:subtotal].to_f.round(2)
    @surcharge = options[:surcharge].to_f.round(2)
    super(school)
  end

  def call
    url = URI.parse("#{base_uri}/#{@endpoint}")
    url.query = URI.encode_www_form(form_params)
    url.to_s
  end

  private
    def timestamp
      @timestamp ||= Time.now.to_i
    end

    def hash_key
      salt = "#{user_id}#{timestamp}"
      OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), user_hash_key, salt)
    end

    def form_params
      {}.tap do |props|
        props[:timestamp] = timestamp
        props[:'developer-id'] = developer_id
        props[:'hash-key'] = hash_key
        props[:'user-id'] = user_id
        props[:data] = if @payform
          { transaction: data }
        else
          { accountvault: data }
        end.to_json.unpack1('H*')
      end
    end

    def data
      {}.tap do |props|
        props[:payment_method] = @options[:payment_method]
        props[:location_id] = location_id
        props[:parent_send_message] = true
        props[:show_street] = true
        props[:show_zip] = true
        props[:billing_street] = @family.address
        props[:billing_zip] = @family.zip
        props[:require_zip] = true
        props[:require_street] = false
        props[:stylesheet_url] = "#{ENV['LEGACY_URL']}/paya.css"

        if @payform
          props[:action] = @options[:payment_method] == 'cc' ? 'sale' : 'debit'
          props[:subtotal_amount] = sprintf('%.2f', @subtotal)
          props[:surcharge_amount] = sprintf('%.2f', @surcharge)
          props[:transaction_amount] = sprintf('%.2f', transaction_amount)
          props[:transaction_api_id] = timestamp.to_s
          props[:product_transaction_id] = @options[:product_transaction_id]
        else
          props[:contact_id] = paya_contact_id
          props[:account_vault_api_id] = timestamp.to_s
          props[:accountvault_c1] = "contact_#{@contact.id}"
          props[:accountvault_c2] = "family_#{@family.id}"
          props[:account_holder_name] = @contact.full_name
          props[:show_account_holder_name] = true
          props[:display_close_button] = false
        end
      end
    end

    def transaction_amount
      (@surcharge + @subtotal).round(2)
    end

    def paya_contact_id
      @options[:paya_contact_id] || @contact.find_or_create_paya_contact(@family)
    end
end
