drop procedure if exists dbo.sp_DeleteFrlloRemainsProcess;
drop procedure if exists public.sp_DeleteFrlloRemainsProcess;
-- =============================================
-- Author:      Vitacore (с) Anatoliy
-- Create date: 2024 11 26
-- Description: Удаление данных ФРЛЛО
-- =============================================
create or replace procedure rds.sp_DeleteFrlloRemainsProcess
(
	"Id" uuid,
	"OnlyClean" boolean 

)
language plpgsql
as
$$
begin
	if exists (select 1 from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsId = "Id" and Status = 2)
		then raise notice('Удаление запрещено!', 16, 10);
	end if;

	if exists (select 1 from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = "Id" and FrlloStatus <> 400 and FrlloStatus is not null)
		then raise notice('Есть успешно принятые в ФРЛЛО данные. Удаление запрещено!', 16, 10);
	end if;

	loop
		if not exists (select 1 from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = "Id" limit 1) 
			then exit;
		end if;
		delete from RDS.T_EXPORT_FRLLO_REMAINS_DATA 
			where ExportFrlloRemains = "Id" 
			and ctid in (select ctid from RDS.T_EXPORT_FRLLO_REMAINS_DATA where ExportFrlloRemains = "Id" limit 1000);
	end loop;
    
    if(@OnlyClean = 1)
    then 
	    update RDS.T_EXPORT_FRLLO_REMAINS set Status = 0 where ExportFrlloRemainsID = @Id;
    else
	    delete from RDS.T_EXPORT_FRLLO_REMAINS where ExportFrlloRemainsID = "Id";
    end if;
end;
$$;