﻿CREATE PROCEDURE [dbo].[BO_AddUserKnok]
	@knokId			bigint,
	@userId			bigint,
	@AccountId		bigint
	
AS
DECLARE		@TranStarted		BIT,
			@ERROR				SMALLINT,
			@RC					INT,
			@RowCount			INT,
			@ErrorMessage		VARCHAR(100),
			@PlatformUserId		BIGINT,
			@PlatformAccountId	BIGINT,
			@KnokPrice			DECIMAL(22, 8)


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

	BEGIN TRANSACTION
	SET @TranStarted = 1

		SELECT @PlatformUserId = [UserId] FROM Users WHERE [UserTypeId] = 2 --Platform
		SET @PlatformAccountId = (SELECT TOP 1 [AccountId] FROM [Accounts] WHERE [UserId] = @PlatformUserId)

		SELECT @KnokPrice = Price FROM Signals WHERE KnokId = @knokId

		--execute transaction
		EXEC	[dbo].[TRN_Account_TransferMoney]
		@FromUserId = @UserId,
		@FromAccountId = @AccountId,
		@FromExternalReferenceId = NULL,
		@FromWalletAddress = NULL,
		@FromAccountTransactionTypeId = 8, --UserBuyKnok
		@ToUserId = @PlatformUserId,
		@ToAccountId = @PlatformAccountId,
		@ToExternalReferenceId = NULL,
		@ToWalletAddress = NULL,
		@ToAccountTransactionTypeId = 8, --UserBuyKnok
		@Amount = @KnokPrice,
		@AmountUSD = NULL,
		@OperatorId = NULL,
		@Comment = NULL,
		@PendingId = NULL,
		@KnokId = @KnokId

	Insert UserKnoks (UserId, KnokId, BuyDate) VALUES(@userId, @knokId, GETDATE()) -- failure on errors
	IF( @TranStarted = 1 )    
	COMMIT TRANSACTION  
END TRY 
BEGIN CATCH  
	IF( @TranStarted = 1 )    
	ROLLBACK TRANSACTION  
	
	EXEC USP_LogError            
	EXEC USP_RethrowError                       
   
	IF @RC = 0
		SET @RC = 1   ---- Unexpected Error	   
		                     
	RETURN @RC                        
END CATCH
