module PaymentGateways
  class MerchantESolutionsCrypt < PaymentGatewayCrypt
    def self.user_for(params)
      User.find params["eresp_sessionid"].split('-').last
    end

    attr_reader :endpoint_url

    def initialize(user)
      super
      @endpoint_url = "https://#{test? ? 'test' : 'www'}.merchante-solutions.com/jsp/tpg/secure_checkout.jsp".freeze
    end

    def buyer_reference
      [super, @user.id].join('-')
    end

    def fill_fields(response_url, return_url)
      fields = {}
      fields['transaction_type']  = 'T'
      fields['echo_sessionid']    = buyer_reference
      fields['echo_checksum']     = Digest::SHA1.hexdigest(buyer_reference + (payment_gateway_options[:login] || ''))
      fields['profile_id']        = payment_gateway_options[:payhere_profile_id]
      fields['logo_url']          = provider.profile.logo.url || ''
      fields['use_merch_receipt'] = 'Y'
      fields['return_url']        = return_url
      fields['response_url']      = response_url
      fields['cancel_url']        = return_url
      fields['css_url']           = 'https://support.3scale.net/themes/merchant-e-sols.css'
      fields
    end

    def update_user(params)
      return unless success?(params)
      account.credit_card_auth_code = params['card_id']
      account.credit_card_expires_on_year = "20#{params['exp_date'][2..3]}"
      account.credit_card_expires_on_month = params['exp_date'][0..1]
      account.credit_card_partial_number = params['acct_number'][-4..-1]
      account.save!
    end

    def success?(params)
      params['tran_type'] == "Card Store" &&
        params['eresp_checksum'] == Digest::SHA1.hexdigest(buyer_reference + (payment_gateway_options[:login] || ''))
    end
  end
end
