﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE FUNCTION [dbo].[fds__getCompanysContacts]
(	
	@companyids [dbo].[fds__tt__idlist] READONLY
)
RETURNS TABLE 
AS
RETURN 
(
	WITH ps as (
			SELECT [companyid] = p.[partnerId], [contactid] = p.[EntityId] from [mfr__*PartnerSet] as p WHERE p.property = 'Contact:Company' and p.[partnerId] IN (SELECT [Id] FROM @companyids)
			UNION
			SELECT [companyid] = p.[PartnerId], [contactid] = p.[PartnerId] from [mfr__*PartnerSet] as p WHERE p.property = 'Company:Contacts' and p.[EntityId] = (SELECT [Id] FROM @companyids)
	)
	SELECT 
		[CyId] = cyid.[Id]
		,ct.*
		,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END  as bit)
	FROM [dbo].[mfr__contacts] as ct 
		JOIN @companyids as cyid ON ct.[CompanyId] = cyid.[id]
		JOIN [dbo].[mfr__companies] as cy ON cyid.[id] = cy.[id]
	UNION
	SELECT 
		[CyId] = cyid.[Id]
		,ct.*
		,[isMainContact] = CAST( CASE WHEN cy.[MainContactId] is null then 0 WHEN cy.[MainContactId] = ct.[id] THEN 1 ELSE 0 END  as bit)
	FROM [dbo].[mfr__contacts] as ct 
		JOIN ps ON ct.[id] = ps.[contactid]
		JOIN @companyids as cyid ON ps.[CompanyId] = cyid.[id]
		JOIN [dbo].[mfr__companies] as cy ON cyid.[id] = cy.[id]
	
)