
const {api} = require("../api/prisma")
const {database} =require('../mongo-connector')
const system = require('system-commands')


function formatPrismaSchema(){
 // system("npx prisma format")
}

async function syncRole(config){
 // Initialize the Public Role
 var roles = await api.findMany('Roles',{
        
 }).then(e=>e)
 .catch(err=>[])

 config.roles = roles

 var init ={
   rolePublic: roles.filter(e=>e?.name?.toLowerCase()=='public')||[]
 }
 config.init = {
   ...config.init,
   ...init
 }
}


async function Initialize(config){
   formatPrismaSchema()
   await syncRole(config)

}

async function InitializeCache(config){
  config.cachesConfig = await api.findMany('vcaches',{
  }).then(e=>e)
  .catch(err=>[])
}

async function setAllCache(c,config){
 if(config.redis.isOk){
  var params = c?.params || {}
  var res = await api.findMany(c.model,params).then(e=>e).catch(err=>[])
  config.caches.set(`vcaches:${c.name}`,JSON.stringify(res))
 }
}

function InitializeWatchStream(config){

  if(config?.redis?.cache && config?.redis?.isOk){
    for (var c of config.cachesConfig||[]){
      if(!c?.active) return false
      setAllCache(c,config)
      database.collection(c.model).watch().on("change",()=>{
        setAllCache(c,config)
      })

}
}




}

function WatchInitialize(config){
  database.collection("Roles").watch().on("change",(ev)=>{
    Initialize(config)
  })
  database.collection("vcaches").watch().on("change",(ev)=>{
    InitializeCache(config)
  })

 
}


module.exports={
    Initialize,
    WatchInitialize,
    InitializeWatchStream,
    InitializeCache
}