#! /usr/bin/env node
const consola =require("consola")

const {execSync} = require('child_process')
const path =require("path")
const fs = require('fs')
const folders_extensions =['endpoints','plugins','services','tasks','api']
const root_folders = ['admin','uploads']
const runCommand=(action,element='',args)=>{
var pkg = args.find(opt=>opt=='--pnpm') ? 'pnpm':'npm'
    try{
      if(action=='revert'){
        execSync('rsync -a .tmp/.collections/ ./collections')
        execSync('rsync -a node_modules/@bitev.io/core/bin/schema.prisma ./prisma')
        // status of init project
           console.log('\n')
           consola.success("Revert action done ")
      }

      if(action=='features'){
       // execSync('rsync -a .tmp/.collections/ ./collections')
        execSync(`rsync  node_modules/@bitev.io/core/features/collections/${elementName}.js ./collections/`)
        // status of init project
        console.log('\n')
        consola.success(`Feature ${elementName} done `)
      }

      if(action=='update') {
            // Folder extensions
            console.log(process.cwd()) 
            folders_extensions.map(folder=>{
             let dir = process.cwd()+'/extensions/'+folder
               if(fs.existsSync(dir)){

               } else {
                fs.mkdirSync(dir)
                
               }
            })

            // root folders
            root_folders.map(folder=>{
                let dir = process.cwd()+'/'+folder
                  if(fs.existsSync(dir)){
   
                  } else {
                   fs.mkdirSync(dir)
                   
                  }
               })

            execSync(`${pkg} i prisma-json-schema-generator && ${pkg} i @bitev.io/core@latest && ${pkg} i @prisma/client@latest && ${pkg} i prisma@latest -D && npx prisma generate`,{stdio:'inherit'})

// status of init project
console.log('\n')
consola.success("Project updated to latest version of bitev.io CMS ")
        
          }
    } catch(err){

        consola.error(`Failed to execute ${action} ${elementName} `,err)
        return false

    }

    return true

} 

const actionName=process.argv[2];
const elementName=process.argv[3];

var execCommand = runCommand(actionName,elementName,process.argv)
if(!execCommand) process.exit(-1)

