Delimiter $$
/**
 * Author:  armen
 * Created: 3 jan. 2024
 * remplit la table TMP_ACCOUNTS_has_MEMBERS depuis la table TMP_ACCOUNTS_has_MEMBERS_SAVE
 * afin de ré-actualiser les accreditations des correspondants
 */
# Delimiter $$
Drop Procedure if Exists BUSINESS_ATTACHED_MEMBERS_RESTORE_SAVED_RULES$$
Create Procedure BUSINESS_ATTACHED_MEMBERS_RESTORE_SAVED_RULES(
        in entity Int unsigned
        , in rulesRef VARCHAR(35)
    )
Begin
    bamrsr_main: begin
        -- creation de la table de sauvegarde si nécéssaire
        -- pas de purge
        call LOADER_CREATE_TABLE_TMP_ACC_HAS_MBR_SAVE();
        set @bamrsr_rulesRef = Coalesce(rulesRef, '%');

        set @bamrsr_entity_min = Coalesce(entity, 1);
        set @bamrsr_entity_max = Coalesce(entity, 10000);

        Set @bamrsr_newRefAuto = Concat('AUTO.', md5(now()));
        -- debug
        -- set @bamrsr_entity_min = 1;  set @bamrsr_entity_max = 10000
        -- set @bamrsr_entity_min = 1;  set @bamrsr_entity_max = 1
        -- set @bamrsr_rulesRef = '%';

        bamrsr_prep: begin
            Delete tar From TMP_ACCOUNTS_has_MEMBERS tar;
        end ;

        bamrsr_cpy: begin

            Insert Into TMP_ACCOUNTS_has_MEMBERS (
                       ACCOUNTS_ID_ACCOUNTS, MEMBERS_ID_MEMBERS, ENTITIES_ID_ENTITIES
                     , ENT_REF_DATA_ID_ENT_REF_DATAS_1, ENT_REF_DATA_ID_ENT_REF_DATAS_2
                     , ENT_REF_DATA_ID_ENT_REF_DATAS_3, ENT_REF_DATA_ID_ENT_REF_DATAS_4
                     , ENT_REF_DATA_ID_ENT_REF_DATAS_5
                     , DF_ACCESS_PROFILES_ID_DF_ACCESS_PROFILES
                     , TMP_ACCOUNTS_has_MEMBERS_REF
                )
            Select
               Distinct
                ACCOUNTS_ID_ACCOUNTS, MEMBERS_ID_MEMBERS, ENTITIES_ID_ENTITIES
                , ENT_REF_DATA_ID_ENT_REF_DATAS_1, ENT_REF_DATA_ID_ENT_REF_DATAS_2
                , ENT_REF_DATA_ID_ENT_REF_DATAS_3, ENT_REF_DATA_ID_ENT_REF_DATAS_4
                , ENT_REF_DATA_ID_ENT_REF_DATAS_5
                , DF_ACCESS_PROFILES_ID_DF_ACCESS_PROFILES
                , Case
                    When TMP_ACCOUNTS_has_MEMBERS_REF Is NULL Then ''
                    When TMP_ACCOUNTS_has_MEMBERS_REF like 'AUTO.%' Then @bamrsr_newRefAuto
                    Else TMP_ACCOUNTS_has_MEMBERS_REF
                End
            From
                TMP_ACCOUNTS_has_MEMBERS_SAVE
            Where ENTITIES_ID_ENTITIES between @bamrsr_entity_min  And @bamrsr_entity_max
                And TMP_ACCOUNTS_has_MEMBERS_REF like @bamrsr_rulesRef
            ;
        end ;


    end ;
end $$