/**
  @file
  @brief Post Edit Hook script for the MPE_ROW_LEVEL_SECURITY table
  @details Post edit hooks provide additional backend validation for user
  provided data.  The incoming dataset is named `work.staging_ds` and is
  provided in mpe_loader.sas.

  Available macro variables:
    @li DC_LIBREF - The DC control library
    @li LIBREF - The library of the dataset being edited (is assigned)
    @li DS - The dataset being edited

  This validation checks the incoming row_level_security settings to ensure
  each individual filter is

  <h4> SAS Macros </h4>
  @li dc_assignlib.sas
  @li mp_filtercheck.sas

  <h4> Related Macros </h4>
  @li mpe_loader.sas

**/


/* ignore scope and group for validation */
proc sql;
create table work.batches as
  select distinct upcase(rls_libref) as rls_libref,
    upcase(rls_table) as rls_table,
    rls_group_logic as group_logic,
    rls_subgroup_logic as subgroup_logic,
    rls_subgroup_id as subgroup_id,
    rls_variable_nm as variable_nm,
    rls_operator_nm as operator_nm,
    rls_raw_value as raw_value
  from work.staging_ds
  where rls_active=1
  order by rls_libref, rls_table;

%let cnt=0;
data _null_;
  set work.batches;
  by rls_libref rls_table;
  putlog (_all_)(=);
  if last.rls_table then do;
    x+1;
    call symputx(cats('libds',x),cats(rls_libref,'.',rls_table));
    call symputx('cnt',x);
  end;
run;

%macro quickloop();
%do i=1 %to &cnt;
  data work.inds&i;
    set work.batches;
    if cats(rls_libref,'.',rls_table)="&&libds&i";
    keep group_logic subgroup_logic subgroup_id variable_nm operator_nm
      raw_value;
  run;
  %dc_assignlib(READ,%scan(&&libds&i,1,.))
  %mp_filtercheck(work.inds&i
    ,targetds=&&libds&i
    ,outds=work.badrecords
    ,abort=YES
  )
%end;
%mend quickloop;

%quickloop()