﻿CREATE PROCEDURE [BO_GetKnokserProfile]
	@KnokserId BIGINT
AS
   SELECT k.UserId, k.UserName, k.FirstName, k.LastName, k.[Rank] as KnokserRank, k.HasAvatar, 
		ISNULL(follow.UserFollowers, 0) UserFollowers, ISNULL(purchases.UserKnoks, 0) Purchases,
		(CASE WHEN EXISTS( select 1 from UserFollows e where e.UserId = @KnokserId and e.FollowUserId = k.UserId) 
			THEN CAST (1 AS BIT) ELSE CAST (0 AS BIT) END) IsFollowed,
		k.RegistrationDate, 0 as RatingPoints, 
		(SELECT SUM(acctran.Amount) 
			FROM [dbo].[AccountTransactions] acctran
			INNER JOIN Signals knok ON knok.KnokId = acctran.KnokId
			WHERE acctran.AccountTransactionTypeId = 8 AND acctran.Amount > 0 AND knok.CreatorUserId = k.UserId) as BoughtBy,
			k.DistanceFromTarget, k.SuccessRate, published.PublishedKnoks, k.SuccessSequence
	FROM [Users] k
	LEFT JOIN (select s.CreatorUserId as userId, count(1) PublishedKnoks  from [dbo].[Signals] s where not KnokStatusId in (1, 2) group by s.CreatorUserId) published on published.userId = k.UserId
	LEFT JOIN (select count(f.UserId) UserFollowers, f.FollowUserId userId from [dbo].[UserFollows] f group by f.FollowUserId) follow on follow.userId = k.UserId
	LEFT JOIN (select count(f.UserId) UserKnoks, knok.CreatorUserId
		from [dbo].[UserKnoks] f 
		inner join Signals knok on f.KnokId = knok.KnokId
		group by knok.CreatorUserId) purchases on  purchases.CreatorUserId = @KnokserId
	WHERE k.UserId = ISNULL(@KnokserId, k.UserId) 
RETURN 0