
const { cleanPath } = require("../utilities/utils");
const fs =require('fs')
var _ = require("lodash");
async function loadModels(config) {
  var Path = cleanPath(process.cwd()  + "/prisma/models/json-schema.json");
  return new Promise(function (resolve, reject) {
    glob(Path, {}, async function (er, files) {
      // register all endpoints
      var models = {
      }
      files.map((file) => {
      let model = require("" + file);
      if(model){
        
        Object.keys(model.definitions).map((mdl,i)=>{

         // console.log('LL',mdl,model.definitions[mdl])

         // console.log(mdl,model.definitions[mdl]?.properties)
          models[mdl.toLowerCase()] = model.definitions[mdl]?.properties
         })
      }
      });

     
      var modelsToArray =Object.keys(models)
      var modelPermissions ={}

      
      await generateCollection({...models})
      modelsToArray.map(key=>{
        modelPermissions[key]={
          actions:[], // Can CRUD
          view:true, // 
        }
      })

      config.collections.permissions=modelPermissions
      config.collections.models = {
        ...models,
      }
      //console.log(config.models)

    //consola.success(`${Object.keys(models).length} Models charged`);

      // files is an array of filenames.
      // If the `nonull` option is set, and nothing
      // was found, then files is ["**/*.js"]
      // er is an error object or null.
      resolve();
    });
  });
}


async function generateCollection(models={}){

return new Promise(async(resolve)=>{
  var modelsToArray =Object.keys(models)



  
 
  modelsToArray.map(folder=>{
    
    folder = folder.toLowerCase()
  
    if(folder.match(/^(cda|roles|acl|insights|webhooks|flows)$/)) return ;
    // Create folder
    let dir = cleanPath(process.cwd()+'/extensions/api/'+folder);
    !fs.existsSync(dir) ?  fs.mkdirSync(dir):null;


    // Create Hooks files
    let hook = cleanPath(process.cwd()+'/extensions/api/'+folder+`/hooks.${folder}.js`);
    let jsonHook =`//Hooks 
    module.exports ={
    }
    `
    !fs.existsSync(hook) ?  fs.writeFileSync(hook, jsonHook,()=>{}) :'';

   


   // Create file schema file
    let jsonSchema =`
    // Model Configuration toolkit
    // Ajv JSON schema validator Security and reliability for JavaScript applications
    // https://ajv.js.org/json-schema.html
    module.exports={
      validationState:false, // Disable or enable AJV validation
      validationAPI:['createUnique'], // validation for theses hooks - createunique|updateUnique|updateUnique|updateMany
      validationSchema:{ // AJV Schema
      }
    }`
    let schema = process.cwd()+'/extensions/api/'+folder+`/schema.${folder}.js`
    !fs.existsSync(schema) ?  fs.writeFile(schema, jsonSchema,()=>{}) :''
    resolve()
  })
})

}


module.exports = {
  loadModels,
};
