
const {api} =require('../api/prisma')
const _ =require("lodash")
const cleanDeep =require("clean-deep")

async function loadmodelviews(config){

 
try{
    var modelviews = await api.findMany("modelviews").then(e=>e).catch(err=>{
        return []
    })
    config.modelviews = modelviews
} catch(err){

}


}



function updateModelViews(model=null,config){

    if(model && model=='modelviews' ){
        loadmodelviews(config)
    }

}


async function apiModelviews(config,req,res,next){

try{


    //console.log(req.state)

    var model = req.params.model
    var allModelsiews = config.modelviews
    var isView = allModelsiews.find(e=>e.name==model)

    if(isView.id){

  //  console.log(req.state)
 //   console.log(isView.rolesIds)
 //   console.log(isView.config.collection)

    var rolesViews = isView.rolesIds || [] 

    if(!rolesViews) return res.send([])
    var results = []
    var includesElements = isView.config.visibleFields.split('\n')
    var col = isView.config.collection
    var includesRelations = {}
    col?.fields.map(e=>{
        if(e.type=='relationship'){
            includesElements[e.name]= true
        }
    })
    var options = {
        include:includesRelations
    }

    

        
        var data = await api.findMany(isView.config.collection.slug,cleanDeep(options)).then(e=>e).catch(err=>[])       
        data.filter((r)=>{
            let topush = _.pick(r,includesElements)
            results.push(topush)
        })


        if(req.state?.auth && req.state?.user?.isRoot){
              return res.send(results)
         }


         if(req.state?.auth && req.state?.user?.role){
            let roleMatch = rolesViews.filter(roleId=>roleId==req.state?.user?.role) ||[]
            if(roleMatch?.length){
                return res.send(results)
            } else{
                return res.status(400).send('unauthorized')
            }

         }


         if(!req.state?.auth){
            let publicRole = await api.findMany('roles',{
                where:{
                    name:'public'
                }
            }).then(e=>e[0]).catch(err=>null)

            if(publicRole){
                let roleMatchPublic = rolesViews.filter(roleId=>roleId==req.state?.user?.role) ||[]
                if(roleMatchPublic?.length) return  res.send(results)
            }

            
         }


         return res.status(400).send('unauthorized')


         

       // console.log(req.state

    } else {

        res.send([])
    }
    


} catch(err){
    console.error(err)
    res.status(400).send(err)
}


}




module.exports={
    loadmodelviews,
    updateModelViews,
    apiModelviews
}