

const merge = require('deepmerge')
var _ = require("lodash");
const moment =require('moment')

const { cleanPath } = require("../utilities/utils");
async function loadPoliciesAPI(config) {

}



async function loadPolicies(config) {
try{
  var Path = cleanPath(process.cwd() + "/api/**/policies.*.js")
  return new Promise(function (resolve, reject) {
    glob(Path, {}, function (er, files) {
      // register all endpoints

     
      var policies = {}    
     
      files.map((file) => {
        
        let police = require("" + file);
       
        if (police?.model) {
          
          policies[police.model] = police;
        } else {
          let policeMissing = file.split('/')
          policies[policeMissing[policeMissing.length - 2]] =police;
        }
       
      });
      config.policies = {
        ...config.policies,
       ...policies,
      }
  
      resolve();
    });
  });

} catch(err){
  console.error(err)
}
}


function evalPocies($USER,$ACTION,$MOMENT,fx){
  var $NOW = $MOMENT().format()
  eval(`var  func =()=>{
    ${fx}
  } `)
  return func()
}


function policiesWhere($USER,$ACTION, model,option){
 const opts ={}
  Object.defineProperty(opts,'$MOMENT',{
    value:moment,
    writable:false,
    enumerable:false,
    configurable:false
  })

  Object.defineProperty(opts,'$USER',{
    value:$USER,
    writable:false,
    enumerable:false,
    configurable:false
  })

  Object.defineProperty(opts,'$ACTION',{
    value:$ACTION,
    writable:false,
    enumerable:false,
    configurable:false
  })


  Object.defineProperty(opts,'$USER',{
    value:$USER,
    writable:false,
    enumerable:false,
    configurable:false
  })


 


  const permissions = opts.$USER?.role?.permissions || {}

  var userPermission = null

  Object.keys(permissions).map(key=>{
   if(key==model)
    userPermission=permissions[key]
  })


  //console.log(userPermission,model)

  if(userPermission && userPermission.policies){   
    var where = evalPocies(opts.$USER,opts.$ACTION,opts.$MOMENT,userPermission.policies)
    option.where =merge(option.where||{},where)      
  }

}


module.exports = {
  loadPoliciesAPI,
  policiesWhere,
  loadPolicies
};
