module DeveloperPortal::Admin::Account
  class PaymentExpressController < PaymentDetailsBaseController
    def show
      @payment_gateway_url = ::PaymentGateways::PaymentExpressCrypt.auth_url(
        login: site_account.payment_gateway.options[:hosted_login],
        password: site_account.payment_gateway.options[:hosted_password],
        success_url: hosted_success_admin_account_payment_express_url,
        failure_url: admin_account_payment_express_url
      )

      render template: "accounts/payment_gateways/show"
    end

    def hosted_success
      auth_response = hosted_success_auth_response

      if update_credit_card(auth_response)
        flash[:success] = 'Credit card details were successfully authorized.'
      else
        Rails.logger.info '[Payment gateway] Failed to update your credit card details, ' \
                    "result: #{params[:result]}"
        flash[:notice] = 'Failed to update your credit card details. ' \
          'Please check your information is correct.'
      end
      redirect_to after_hosted_success_path
    end

    protected

    def after_hosted_success_without_plan_changes_path
      admin_account_payment_express_path
    end

    # FIXME: This should part of some model or service
    # We still use mass assignment + white/black list so explicitly settings attributes here
    def update_credit_card(auth_response)
      current_account.credit_card_auth_code = auth_response[:auth_code]
      current_account.credit_card_expires_on = Date.strptime(auth_response[:expiry_date], '%m%y')
      current_account.credit_card_partial_number = auth_response[:card_number][0..3]
      current_account.save
    end

    def hosted_success_auth_response
      ::PaymentGateways::PaymentExpressCrypt
        .auth_response(
          login: site_account.payment_gateway.options[:hosted_login],
          password: site_account.payment_gateway.options[:hosted_password],
          result: params[:result]
        )
    end
  end
end
