/**
  @file
  @brief Post Edit Hook script for the MPE_TABLES 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 MPE_TABLES to ensure modified / added records are
  valid.  If a non-default AUDIT_LIBDS is being used, there is also a check
  to ensure that this table already exists.


**/

%let errmsg=;
%let errflag=0;

/* ensure uppercasing */
data work.staging_ds;
  set work.staging_ds;
  /* PK fields should not be upcased if we are trying to delete records */
  if upcase(_____DELETE__THIS__RECORD_____) ne "YES" then do;
    LIBREF=upcase(LIBREF);
    DSN=upcase(DSN);
  end;
  loadtype=upcase(loadtype);
  buskey=upcase(buskey);
  var_txfrom=upcase(var_txfrom);
  var_txto=upcase(var_txto);
  var_busfrom=upcase(var_busfrom);
  var_busto=upcase(var_busto);
  var_processed=upcase(var_processed);
  close_vars=upcase(close_vars);
  audit_libds=upcase(audit_libds);
  rk_underlying=upcase(rk_underlying);

  /* do not accept certain librefs */
  if LIBREF in ('WORK','CASUSER','SASUSER')
  then do;
    call symputx('errmsg',"Invalid LIBREF: "!!LIBREF);
    call symputx('errflag',1);
  end;

  /* check for valid loadtype */
  if LOADTYPE not in ('UPDATE','TXTEMPORAL','FORMAT_CAT','BITEMPORAL','REPLACE')
  then do;
    call symputx('errmsg',"Invalid LOADTYPE: "!!LOADTYPE);
    call symputx('errflag',1);
  end;

  /* force correct BUSKEY and DSN when loading format catalogs */
  if LOADTYPE='FORMAT_CAT' then do;
    BUSKEY='TYPE FMTNAME FMTROW';
    DSN=scan(dsn,1,'-')!!'-FC';
  end;

  /* convert tabs into spaces */
  buskey=translate(buskey," ","09"x);
  rk_underlying=translate(rk_underlying," ","09"x);
run;

%mp_abort(iftrue=(&errflag=1)
  ,mac=mpe_tables_postedit
  ,msg=%superq(errmsg)
)

/* get distinct list of audit libs */
proc sql;
create table work.liblist as
  select distinct audit_libds
  from work.staging_ds
  where audit_libds not in ('','0', "&dc_libref..MPE_AUDIT")
    and upcase(_____DELETE__THIS__RECORD_____) ne "YES";

/* assign the libs */
data _null_;
  set work.liblist;
  call symputx(cats('lib',_n_),audit_libds);
  libref=scan(audit_libds,1,'.');
  call execute('%dc_assignlib(WRITE,'!!libref!!')');
run;

/* check the audit tables exist */
data _null_;
  set work.liblist;

  if exist(audit_libds,"DATA")=0 then do;
    call symputx('errmsg',
      "Audit Table "!!audit_libds!!" does not exist, or could not be assigned."
    );
    call symputx('errflag',1);
  end;
run;

%mp_abort(iftrue=(&errflag=1)
  ,mac=mpe_tables_postedit
  ,msg=%superq(errmsg)
)

