
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.cachesConfigList = await api.findMany('vcaches',{
  }).then(e=>e)
  .catch(err=>{
    console.error(err)
    return []
  })

  consola.log(`${config?.cachesConfigList?.length||0} caches  are configured`)


}

async function setAllCache(c,config){
 
  try{
    var params = c?.params || {}
    var res = await api.findMany(c.model,params).then(e=>e).catch(err=>[])
    await  config.caches.set(`vcaches:${c?.name}`,JSON.stringify(res),c?.expire||0)
  } catch(err){
    consola.error(`Set cache for ${c.name} failed`,err)
  }

  
 
}

function InitializeWatchStream(config){
  //&& config?.redis?.isOk
  if(config?.redis?.cache ){
    for (var c of config.cachesConfigList){
      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
}