﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE PROCEDURE [dbo].[fis_admin_setUserGroup]
	@authaccount varchar(5)
	,@usergroup_id varchar(5)
	,@name nvarchar(255)
	,@enc_key uniqueidentifier
AS
BEGIN
	SET NOCOUNT ON;

    DECLARE @utcnow datetime = GETUTCDATE();
	DECLARE @auth smallint = [dbo].[fis_admin_getUserAuth](@authaccount);

	DECLARE @createdID as TABLE ([id] varchar(5));

	IF @auth > 1
	BEGIN
		
			MERGE [dbo].[fis_usergroups] as TARGET
				USING (VALUES(	ISNULL(@usergroup_id, [dbo].[fis_fn_id] ('fis_usergroups'))
								,ENCRYPTBYKEY(@enc_key, @name)
						)) as SOURCE([usergroup_id],[name_enc])
				ON TARGET.[usergroup_id] = SOURCE.[usergroup_id]
			WHEN MATCHED THEN
				UPDATE SET
					TARGET.[name_enc] = SOURCE.[name_enc]
				   ,TARGET.[UserModified] = @authaccount
				   ,TARGET.[DateModified] = @utcnow
			WHEN NOT MATCHED BY TARGET THEN
				INSERT
				   ([usergroup_id]
				   ,[name_enc]
				   ,[UserCreated]
				   ,[DateCreated]
				   ,[UserModified]
				   ,[DateModified]
				   ,[UserDeleted]
				   ,[DateDeleted])
			 VALUES
				   (SOURCE.[usergroup_id]
					,SOURCE.[name_enc]
				   ,@authaccount
				   ,@utcnow
				   ,@authaccount
				   ,@utcnow
				   ,NULL
				   ,NULL)
			OUTPUT inserted.[usergroup_id]
				INTO @createdID;


			SELECT TOP(1) * FROM [dbo].[fis_admin_getUserGroupList](@authaccount, @usergroup_id) ual 
				JOIN @createdID as id on ual.[usergroup_id] = id.[id];

	END

END