SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [PRREC_DELETE_OBJECT]
-- =================================================================
-- Deletes one or more data in a given Entity
-- 
-- Returns: INT Value - 0 = Everything worked well
-- =================================================================
-- Copyright (c) 2025 by Digital Data GmbH
--
-- Digital Data GmbH • Ludwig-Rinn-Strasse 16 • D-35452 Heuchelheim
-- Tel.: 0641/202360 • E-Mail: info-flow@digitaldata.works
-- =================================================================
-- Creation Date / Author:    22.12.2025 / MK
-- Version Date / Editor:     22.12.2025 / MK
-- Version Number:            1.0.0.0
-- =================================================================
-- History:
-- 22.12.2025 / MK - First Version

CREATE OR ALTER PROCEDURE [dbo].[PRREC_DELETE_OBJECT] (
	@pENTITY				NVARCHAR(25)	= 'RESULT',		-- Target entity: ACTION, ENDPOINT, ENDPOINT_AUTH, ENDPOINT_PARAMS, PROFILE, RESULT
	@pSTART					NVARCHAR(25)	= '0',			-- Start GUID/ID (inclusive), numeric text
	@pEND					NVARCHAR(25)	= '0',			-- End GUID/ID (inclusive), numeric text
	@pFORCE					BIT				=  0			-- 1 = delete even if dependent data exists
)
AS
BEGIN

	SET NOCOUNT ON;
	SET XACT_ABORT ON;

	-- declare new vars because of parameter sniffing
	DECLARE @ENTITY				NVARCHAR(25)	= UPPER(LTRIM(RTRIM(ISNULL(@pENTITY, 'RESULT')))),
			@START_VAL			NVARCHAR(25)	= LTRIM(RTRIM(ISNULL(@pSTART, '0'))),
			@END_VAL			NVARCHAR(25)	= LTRIM(RTRIM(ISNULL(@pEND, '0'))),
			@FORCE				BIT				= ISNULL(@pFORCE, 0);

	-- declare runtime vars
	DECLARE @MY_PROCEDURE_NAME	NVARCHAR(128)	= OBJECT_NAME(@@PROCID);
	DECLARE @START_ID			BIGINT			= TRY_CAST(@START_VAL AS BIGINT),
			@END_ID				BIGINT			= TRY_CAST(@END_VAL AS BIGINT),
			@END_ID_TMP			BIGINT			= 0,
			@RETURN_STATUS		INT				= 0,
			@RETURN_STATUS_TEXT	NVARCHAR(MAX)	= 'START PROCEDURE [' + @MY_PROCEDURE_NAME + '] @ ' + CONVERT(VARCHAR(50), GETDATE(), 120);	
	----------------------------------------------------------------------------------------------------------------------------

	--=================================================-- Output parameters --================================================--
	PRINT '====================================================================================================';
	PRINT @RETURN_STATUS_TEXT;
	PRINT '';
	PRINT 'PARAMETER01 - @ENTITY: ' + ISNULL(CONVERT(NVARCHAR(25), @ENTITY),    'NULL');
	PRINT 'PARAMETER02 - @START:  ' + ISNULL(CONVERT(NVARCHAR(25), @START_VAL), 'NULL');
	PRINT 'PARAMETER03 - @END:    ' + ISNULL(CONVERT(NVARCHAR(25), @END_VAL),   'NULL');
	PRINT 'PARAMETER04 - @FORCE:  ' + ISNULL(CONVERT(NVARCHAR(1),  @FORCE),     'NULL');
	PRINT '';
	-----------------------------------------------------------------------------------------------------------------------------

	--================================================-- Validation --=======================================================--
	IF (@ENTITY NOT IN ('ACTION', 'ENDPOINT', 'ENDPOINT_AUTH', 'ENDPOINT_PARAMS', 'PROFILE', 'RESULT')) BEGIN
		SET @RETURN_STATUS = 50301;
		SET @RETURN_STATUS_TEXT = 'ERROR: Unknown entity "' + @ENTITY + '". Allowed: ACTION, ENDPOINT, ENDPOINT_AUTH, ENDPOINT_PARAMS, PROFILE, RESULT.';
		RAISERROR(@RETURN_STATUS_TEXT,16,1);
		RETURN @RETURN_STATUS;
	END;

	IF (@START_ID IS NULL OR @END_ID IS NULL) BEGIN
		SET @RETURN_STATUS = 50302;
		SET @RETURN_STATUS_TEXT = 'ERROR: @START and @END must be convertible to BIGINT.';
		RAISERROR(@RETURN_STATUS_TEXT,16,1);
		RETURN @RETURN_STATUS;
	END;

	-- normalize range
	IF (@END_ID = 0) BEGIN
		SET @END_ID     = @START_ID;
	END;
	
	IF (@START_ID = 0) BEGIN
		SET @START_ID   = @END_ID;
	END;
	
	IF (@START_ID > @END_ID) BEGIN
		SET @END_ID_TMP = @START_ID;
		SET @START_ID   = @END_ID;
		SET @END_ID     = @END_ID_TMP;
	END;

	PRINT 'INFO: Normalized deletion range from ' + CONVERT(NVARCHAR(25), @START_ID) + ' to ' + CONVERT(NVARCHAR(25), @END_ID);
	-----------------------------------------------------------------------------------------------------------------------------

	--===============================================-- Main Processing --===================================================--
	BEGIN TRY

		BEGIN TRANSACTION;

		-- Delete selected entities respecting dependencies
		IF (@ENTITY = 'ACTION' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting ACTION records...';

			IF (@FORCE = 0 AND EXISTS (SELECT 1 FROM [dbo].[TBREC_OUT_RESULT] WHERE [ACTION_ID] BETWEEN @START_ID AND @END_ID)) BEGIN
				SET @RETURN_STATUS = 50303;
				SET @RETURN_STATUS_TEXT = 'ERROR: Dependent results exist for ACTION. Set @pFORCE=1 to delete anyway.';
				RAISERROR(@RETURN_STATUS_TEXT,16,1);
				RETURN @RETURN_STATUS;
			END; ELSE BEGIN
				DELETE FROM [dbo].[TBREC_OUT_RESULT] WHERE [ACTION_ID] BETWEEN @START_ID AND @END_ID;
				DELETE FROM [dbo].[TBREC_CFG_ACTION] WHERE [GUID]      BETWEEN @START_ID AND @END_ID;
				SET @RETURN_STATUS_TEXT = 'INFO: ACTION and related RESULT records deleted.';
				PRINT @RETURN_STATUS_TEXT;
			END;
		END;
		ELSE IF (@ENTITY = 'ENDPOINT' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting ENDPOINT records...';

			IF (@FORCE = 0 AND EXISTS (SELECT 1 FROM [dbo].[TBREC_CFG_ACTION] WHERE [ENDPOINT_ID] BETWEEN @START_ID AND @END_ID)) BEGIN
				SET @RETURN_STATUS = 50304;
				SET @RETURN_STATUS_TEXT = 'ERROR: ENDPOINT is used by ACTION. Set @pFORCE=1 to delete anyway.';
				RAISERROR(@RETURN_STATUS_TEXT,16,1);
				RETURN @RETURN_STATUS;
			END; ELSE BEGIN
				DECLARE @ActionIdsForEndpoint TABLE (GUID BIGINT PRIMARY KEY);
				INSERT INTO @ActionIdsForEndpoint(GUID)
				SELECT [GUID] FROM [dbo].[TBREC_CFG_ACTION] WHERE [ENDPOINT_ID] BETWEEN @START_ID AND @END_ID;

				DELETE FROM [dbo].[TBREC_OUT_RESULT]   WHERE [ACTION_ID] IN (SELECT GUID FROM @ActionIdsForEndpoint);
				DELETE FROM [dbo].[TBREC_CFG_ACTION]   WHERE [GUID]      IN (SELECT GUID FROM @ActionIdsForEndpoint);
				DELETE FROM [dbo].[TBREC_CFG_ENDPOINT] WHERE [GUID]      BETWEEN @START_ID AND @END_ID;

				SET @RETURN_STATUS_TEXT = 'INFO: ENDPOINT, related ACTION and RESULT records deleted.';
				PRINT @RETURN_STATUS_TEXT;
			END;
		END;
		ELSE IF (@ENTITY = 'ENDPOINT_AUTH' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting ENDPOINT_AUTH records...';

			IF (@FORCE = 0 AND EXISTS (SELECT 1 FROM [dbo].[TBREC_CFG_ACTION] WHERE [ENDPOINT_AUTH_ID] BETWEEN @START_ID AND @END_ID)) BEGIN
				SET @RETURN_STATUS = 50305;
				SET @RETURN_STATUS_TEXT = 'ERROR: ENDPOINT_AUTH is used by ACTION. Set @pFORCE=1 to delete anyway.';
				RAISERROR(@RETURN_STATUS_TEXT,16,1);
				RETURN @RETURN_STATUS;
			END; ELSE BEGIN
				DECLARE @ActionIdsForAuth TABLE (GUID BIGINT PRIMARY KEY);
				INSERT INTO @ActionIdsForAuth(GUID)
				SELECT [GUID] FROM [dbo].[TBREC_CFG_ACTION] WHERE [ENDPOINT_AUTH_ID] BETWEEN @START_ID AND @END_ID;

				DELETE FROM [dbo].[TBREC_OUT_RESULT]        WHERE [ACTION_ID] IN (SELECT GUID FROM @ActionIdsForAuth);
				DELETE FROM [dbo].[TBREC_CFG_ACTION]        WHERE [GUID]      IN (SELECT GUID FROM @ActionIdsForAuth);
				DELETE FROM [dbo].[TBREC_CFG_ENDPOINT_AUTH] WHERE [GUID] BETWEEN @START_ID AND @END_ID;

				SET @RETURN_STATUS_TEXT = 'INFO: ENDPOINT_AUTH, related ACTION and RESULT records deleted.';
				PRINT @RETURN_STATUS_TEXT;
			END;
		END;
		ELSE IF (@ENTITY = 'ENDPOINT_PARAMS' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting ENDPOINT_PARAMS records...';

			IF (@FORCE = 0 AND EXISTS (SELECT 1 FROM [dbo].[TBREC_CFG_ACTION] WHERE [ENDPOINT_PARAMS_ID] BETWEEN @START_ID AND @END_ID)) BEGIN
				SET @RETURN_STATUS = 50306;
				SET @RETURN_STATUS_TEXT = 'ERROR: ENDPOINT_PARAMS is used by ACTION. Set @pFORCE=1 to delete anyway.';
				RAISERROR(@RETURN_STATUS_TEXT,16,1);
				RETURN @RETURN_STATUS;
			END; ELSE BEGIN
				DECLARE @ActionIdsForParams TABLE (GUID BIGINT PRIMARY KEY);
				INSERT INTO @ActionIdsForParams(GUID)
				SELECT [GUID] FROM [dbo].[TBREC_CFG_ACTION]   WHERE [ENDPOINT_PARAMS_ID] BETWEEN @START_ID AND @END_ID;

				DELETE FROM [dbo].[TBREC_OUT_RESULT]          WHERE [ACTION_ID] IN (SELECT GUID FROM @ActionIdsForParams);
				DELETE FROM [dbo].[TBREC_CFG_ACTION]          WHERE [GUID]      IN (SELECT GUID FROM @ActionIdsForParams);
				DELETE FROM [dbo].[TBREC_CFG_ENDPOINT_PARAMS] WHERE [GUID] BETWEEN @START_ID AND @END_ID;

				SET @RETURN_STATUS_TEXT = 'INFO: ENDPOINT_PARAMS, related ACTION and RESULT records deleted.';
				PRINT @RETURN_STATUS_TEXT;
			END;
		END;
		ELSE IF (@ENTITY = 'PROFILE' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting PROFILE records...';

			IF (@FORCE = 0 AND EXISTS (SELECT 1 FROM [dbo].[TBREC_CFG_ACTION] WHERE [PROFILE_ID] BETWEEN @START_ID AND @END_ID)) BEGIN
				SET @RETURN_STATUS = 50307;
				SET @RETURN_STATUS_TEXT = 'ERROR: PROFILE is used by ACTION. Set @pFORCE=1 to delete anyway.';
				RAISERROR(@RETURN_STATUS_TEXT,16,1);
				RETURN @RETURN_STATUS;
			END; ELSE BEGIN
				DECLARE @ActionIdsForProfile TABLE (GUID BIGINT PRIMARY KEY);
				INSERT INTO @ActionIdsForProfile(GUID)
				SELECT [GUID] FROM [dbo].[TBREC_CFG_ACTION] WHERE [PROFILE_ID] BETWEEN @START_ID AND @END_ID;

				DELETE FROM [dbo].[TBREC_OUT_RESULT]  WHERE [ACTION_ID]  IN (SELECT GUID FROM @ActionIdsForProfile);
				DELETE FROM [dbo].[TBREC_CFG_ACTION]  WHERE [GUID]       IN (SELECT GUID FROM @ActionIdsForProfile);
				DELETE FROM [dbo].[TBREC_RUN_PROFILE] WHERE [PROFILE_ID] BETWEEN @START_ID AND @END_ID;
				DELETE FROM [dbo].[TBREC_CFG_PROFILE] WHERE [GUID]       BETWEEN @START_ID AND @END_ID;

				SET @RETURN_STATUS_TEXT = 'INFO: PROFILE, related ACTION, RESULT and RUN records deleted.';
				PRINT @RETURN_STATUS_TEXT;
			END;
		END;
		ELSE IF (@ENTITY = 'RESULT' AND @RETURN_STATUS = 0) BEGIN
			PRINT 'INFO: Deleting RESULT records...';
			DELETE FROM [dbo].[TBREC_OUT_RESULT] WHERE [GUID] BETWEEN @START_ID AND @END_ID;
			SET @RETURN_STATUS_TEXT = 'INFO: RESULT records deleted.';
			PRINT @RETURN_STATUS_TEXT;
		END;

		IF (@RETURN_STATUS > 0) BEGIN
			IF (XACT_STATE() <> 0) ROLLBACK TRANSACTION;
		END; ELSE BEGIN
			COMMIT TRANSACTION;
		END;

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS_TEXT = 'END PROCEDURE [' + @MY_PROCEDURE_NAME + '] @ ' + CONVERT(VARCHAR(50), GETDATE(), 120);

		PRINT '';
		PRINT @RETURN_STATUS_TEXT;
		PRINT '====================================================================================================';
		-----------------------------------------------------------------------------------------------------------------------------------
		
		RETURN @RETURN_STATUS;

	END TRY BEGIN CATCH

		IF (XACT_STATE() <> 0) ROLLBACK TRANSACTION;

		--======================================================-- Output result --======================================================--
		SET @RETURN_STATUS_TEXT = 'ERROR: ' + ERROR_MESSAGE();
		RAISERROR(@RETURN_STATUS_TEXT,16,1);

		SET @RETURN_STATUS_TEXT = 'END PROCEDURE [' + @MY_PROCEDURE_NAME + '] @ ' + CONVERT(VARCHAR(50), GETDATE(), 120);

		PRINT '';
		PRINT @RETURN_STATUS_TEXT;
		PRINT '====================================================================================================';
		-----------------------------------------------------------------------------------------------------------------------------------

		RETURN @RETURN_STATUS;

	END CATCH;
	-----------------------------------------------------------------------------------------------------------------------------

END;
GO