IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DeleteFrlloRemainsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_DeleteFrlloRemainsProcess]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[rds].[sp_DeleteFrlloRemainsProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [rds].[sp_DeleteFrlloRemainsProcess]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2023 11 24
-- Description: Удаление данных ФРЛЛО
-- =============================================
CREATE PROCEDURE [rds].[sp_DeleteFrlloRemainsProcess]
    @Id uniqueidentifier,
    @OnlyClean bit,
    @RemovalAllowed bit
AS
BEGIN
    if (exists (select 1 from RDS.T_FRLLO_MESSAGE where ExportFrlloRemains = @Id))
    begin
        if (@RemovalAllowed = 1)
        begin
            delete from RDS.T_FRLLO_MESSAGE where ExportFrlloRemains = @Id
        end
        else
        begin
            raiserror('Нельзя удалить запись, так как существуют связанные сообщения', 16, 1)
            return
        end
    end

    if (exists (select 1 from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsId = @Id and [Status] = 2))
	begin
        RAISERROR('Удаление запрещено!', 16, 10) 
        return
	end
	if (exists (select 1 from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = @Id and FrlloStatus <> 400 and FrlloStatus is not null))
	begin
        RAISERROR('Есть успешно принятые в ФРЛЛО данные. Удаление запрещено!', 16, 10) 	
        return
	end

	WHILE EXISTS(SELECT TOP 1 1 FROM RDS.T_EXPORT_FRLLO_REMAINS_DATA WHERE ExportFrlloRemains = @Id)
	BEGIN
		delete TOP(1000) from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = @Id
	END

    if (@OnlyClean = 1)
    begin 
	    update RDS.T_EXPORT_FRLLO_REMAINS set Status = 0 where ExportFrlloRemainsID = @Id
    end
    else
	    delete from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsID = @Id

END

