CREATE OR REPLACE PROCEDURE RDS.sp_UpdateDispDirectList(
    OUT cnt INT
)
    LANGUAGE plpgsql
AS
$$
BEGIN
    SELECT
        COUNT(*)
    INTO cnt
    FROM RDS.T_DISP_DIRECT;

    INSERT INTO
        RDS.t_disp_direct(DispDirectId,
                          id_pac,
                          fam,
                          im,
                          ot,
                          dr,
                          spolis,
                          npolis,
                          docser,
                          docnum,
                          year,
                          w,
                          doctype,
                          snils_p,
                          snils_d,
                          vpolis,
                          code_smo,
                          code_mo,
                          enp)
    SELECT
        gen_random_uuid(),
        p.patientid,
        p.lastname,
        p.firstname,
        p.fathername,
        p.birthday,
        p.polisserial,
        p.polisnumber,
        p.docseries,
        p.docnumber,
        EXTRACT(YEAR FROM CURRENT_TIMESTAMP),
        p.sex,
        p.doctype,
        p.snils,
        p.snils_d,
        p.policyform,
        p.f002smo,
        p.lpumain,
        p.Enp
    FROM RDS.T_PATIENT p
    WHERE
          (EXTRACT(YEAR FROM CURRENT_TIMESTAMP) - EXTRACT(YEAR FROM CURRENT_TIMESTAMP))::INT % 3 = 0
      AND (EXTRACT(YEAR FROM CURRENT_TIMESTAMP) - EXTRACT(YEAR FROM CURRENT_TIMESTAMP))::INT BETWEEN 21 AND 99
      AND NOT EXISTS(SELECT
                         dd.*
                     FROM RDS.t_disp_direct dd
                     WHERE
                         dd.enp = p.enp);

    SELECT
        COUNT(*) - cnt
    INTO cnt
    FROM RDS.t_disp_direct;
END;
$$;