DROP PROCEDURE IF EXISTS AKUZ.sp_UpdateCurrentsInPsychoDispInit;

CREATE PROCEDURE AKUZ.sp_UpdateCurrentsInPsychoDispInit(
    IN DispanserisationInitId UUID
)
LANGUAGE plpgsql
AS $$
BEGIN
    -- Создаем временную таблицу для хранения актуальных данных
    CREATE TEMP TABLE TempDispData (
        DispanserisationInit UUID PRIMARY KEY,
        Mkb VARCHAR(255),
        Diagnosis VARCHAR(255),
        SurveillanceType INT,
        DnGroup INT,
        MentalDispanserisationType INT,
        DnSubGroup INT
    ) ON COMMIT DROP;

    -- Заполняем временную таблицу актуальными записями
    INSERT INTO TempDispData
    SELECT 
        mmov.DispanserisationInit,
        mmov.Mkb,
        mmov.Diagnosis,
		mov.SurveillanceType,
		mov.DnGroup,
		mov.MentalDispanserisationType,
		mov.DnSubGroup
    FROM AKUZ.T_PSYCHO_DISPANSERISATION_MOVENMENT mov
    JOIN AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mmov
		ON mov.MedicalRecordID = mmov.MedicalRecordID
    WHERE 
        mmov.DispanserisationInit = DispanserisationInitId
        AND NOT EXISTS (
            SELECT 1
            FROM AKUZ.T_MENTAL_DISPANSERISATION_MOVENMENT mov2
            WHERE mmov.DispanserisationInit = mov2.DispanserisationInit
            AND mov2.DateEditing > mmov.DateEditing
        );


    -- Обновляем T_MENTAL_DISPANSERISATION_INIT
    UPDATE AKUZ.T_MENTAL_DISPANSERISATION_INIT di
    SET 
        CurrentMkb = COALESCE(tmp.Mkb, di.Mkb),
        CurrentDiagnosis = COALESCE(tmp.Diagnosis, di.Diagnosis)
    FROM TempDispData tmp 
    WHERE di.MedicalRecordID = tmp.DispanserisationInit
      AND di.MedicalRecordID = DispanserisationInitId;

    -- Обновляем T_PSYCHO_DISPANSERISATION_INIT (оставляя старые поля)
    UPDATE AKUZ.T_PSYCHO_DISPANSERISATION_INIT pdi
    SET
        CurrentSurveillanceType = COALESCE(tmp.SurveillanceType, pdi.SurveillanceType),
        CurrentDnGroup = COALESCE(tmp.DnGroup, pdi.DnGroup),
        CurrentMentalDispanserisationType = COALESCE(tmp.MentalDispanserisationType, pdi.PsychoDispanserisationType),
        CurrentDnSubGroup = COALESCE(tmp.DnSubGroup, pdi.DnSubGroup)
    FROM TempDispData tmp 
    WHERE pdi.MedicalRecordID = tmp.DispanserisationInit
      AND pdi.MedicalRecordID = DispanserisationInitId;
END $$;
