﻿CREATE PROCEDURE [dbo].[TRN_Account_TransferMoney]
		@FromUserId						bigint
		,@FromAccountId					bigint
		,@FromExternalReferenceId		varchar(66)		= NULL
		,@FromWalletAddress				varchar(42)
		,@FromAccountTransactionTypeId	tinyint -- FreeTokenCredit = 1, Deposit = 2, Withdraw = 3, PublishKnok = 4, KnokerWinsToken = 5, UserBuyKnok = 8, UserRefundToken = 9

		,@ToUserId						bigint
		,@ToAccountId					bigint
		,@ToExternalReferenceId			varchar(66)		= NULL
		,@ToWalletAddress				varchar(42)
		,@ToAccountTransactionTypeId		tinyint -- FreeTokenCredit = 1, Deposit = 2, Withdraw = 3, PublishKnok = 4, KnokerWinsToken = 5, UserBuyKnok = 8, UserRefundToken = 9

		,@Amount						decimal(22,8)
		,@AmountUSD						decimal(18,2)

		,@OperatorId					int
		,@Comment						nvarchar(1000)	= NULL
		
		,@PendingId						bigint			= NULL

		,@KnokId						bigint			= NULL

AS

SET NOCOUNT ON

DECLARE
		@TranStarted					bit,
		@RC								int,
		@ErrorMessage					nvarchar(1000),
		@TransId						bigint

		
BEGIN TRY 
	SET @RC = 0
	SET	@TranStarted = 0

	IF( @@TRANCOUNT = 0 )            
	BEGIN            
		BEGIN TRANSACTION            
		SET @TranStarted = 1            
	END            
	ELSE            
		SET @TranStarted = 0  
	
		EXECUTE @RC = [dbo].[TRN_Account_SetBalance] 
		   @FromUserId
		  ,@FromAccountId
		  ,@FromAccountTransactionTypeId
		  ,@Amount
		  ,@AmountUSD
		  ,@FromExternalReferenceId
		  ,@OperatorId
		  ,@Comment
		  ,@FromWalletAddress
		  ,@PendingId
		  ,1 --@IsUserTransactionDonor
		  ,@KnokId
		  ,@TransId OUTPUT

		  EXECUTE @RC = [dbo].[TRN_Account_SetBalance] 
		   @ToUserId
		  ,@ToAccountId
		  ,@ToAccountTransactionTypeId
		  ,@Amount
		  ,@AmountUSD
		  ,@ToExternalReferenceId
		  ,@OperatorId
		  ,@Comment
		  ,@ToWalletAddress
		  ,@PendingId
		  ,0 --@IsUserTransactionDonor
		  ,@KnokId
		  ,@TransId OUTPUT

	IF( @TranStarted = 1 )            
		COMMIT TRANSACTION            

	RETURN 0

END TRY           
BEGIN CATCH            
    IF( @TranStarted = 1 )            
		ROLLBACK TRANSACTION            

	EXEC [USP_LogError]           
	EXEC [USP_RethrowError]   
	
	IF @RC = 0 
		SET @RC = 1			         
	RETURN @RC
END CATCH