-- =============================================
-- Author:		Vitacore
-- Create date: 2023/08/15
-- Description:	Процедура апдейтит поля у AMBULANCE_CARD State 
-- =============================================
drop procedure if exists sp_UpdateStateAmbulanceCard;
CREATE procedure sp_UpdateStateAmbulanceCard
(
    "PatientID" uuid
)
AS
$BODY$
declare	_StateID UUID;
	_LpuID UUID;
	_Status int;
Begin
    select into 
        _StateID, _LpuID, _Status
        r.State, r.LpuMain, r.Status
	from akuz.T_REGISTRATION r
	where r.Patient = "PatientID" 
	and r.RegistrationDate <= now() 
	and r.AttachmentStatus > 0
	AND r.Profile in (1, 2)
	order by r.RegistrationDate desc		
	Limit 1;
    
    update AKUZ.T_AMBULANCE_CARD
	set State = (case when _Status = 1 and _LpuID = CardLpu then _StateID else null end)
	where Patient = "PatientID";

    return;
End;
$BODY$
  LANGUAGE plpgsql;