﻿CREATE PROCEDURE [BO_PublishKnok]
	@KnokId				BIGINT,
	@UserId				BIGINT,
	@AccountId			BIGINT,
	@PublishPrice		DECIMAL(22, 8),
	--@KnokPrice			DECIMAL(22, 8) = 0.51,
	@PublishPriceUsd	DECIMAL(22, 8) = NULL,
	@KnokRating			DECIMAL(22, 8)
AS
	DECLARE @TranStarted	BIT,
			@ERROR	SMALLINT,
			@RC	INT,
			@RowCount	INT,
			@ErrorMessage	VARCHAR(100),
			@PlatformUserId BIGINT,
			@PlatformAccountId BIGINT
	
BEGIN TRY  
	SET @TranStarted = 0 
	SET @RC	 = 0 

	BEGIN TRANSACTION
	SET @TranStarted = 1

	DECLARE @date datetime
	SET @date = GETUTCDATE()
	update [Signals]
	SET [PublishedDate] = @date,  [KnokStatusId] = 3, [SellFinishDate] = DATEADD(day, 1, @date), [Price] = @PublishPrice
	
	--@KnokRating
	--FROM (SELECT @date PublishedDate, 3 StatusId, DATEADD(day, 1, @date) FinishDate, R.RankValue TokenPrice from API_CalcKnokRanks(@KnokId) R) As V
	Where KnokId = @KnokId and EXISTS(SELECT 1 FROM [_KnokStatuses] s WHERE s.KnokStatusId = Signals.KnokStatusId AND s.IsPublished = 0) 

	IF @@ROWCOUNT = 0  
	BEGIN 
		SET @RC = 1
		SET @ErrorMessage = 'Knok with KnokId = ' + cast (@KnokId as varchar)  + ' does not exists or is published already'
		RAISERROR (@ErrorMessage,16,1);        
	END 
	

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

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

	IF( @TranStarted = 1 )    
		COMMIT TRANSACTION  
	EXEC BO_GetKnoksFull @KnokId
	
	RETURN 0 
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
GO