const Middleware = require('libflitter/middleware/Middleware')

/*
 * GuaranteeRootNode Middleware
 * -------------------------------------------------------------
 * Put some description here!
 */
class GuaranteeRootNode extends Middleware {
    static get services() {
        return [...super.services, 'models']
    }

    /*
     * Run the middleware test.
     * This method is required by all Flitter middleware.
     * It should either call the next function in the stack,
     * or it should handle the response accordingly.
     */
    async test(req, res, next, args = {}){
        const Page = this.models.get('api:Page')
        if ( req.user ) {
            const root_page = await Page.findOne({ OrgUserId: req.user._id, ParentId: "0" })
            if ( !root_page ) {
                const new_page = new Page({
                    Name: `${req.user.uid} virtual root`,
                    OrgUserId: req.user._id,
                    ParentId: "0",
                    CreatedUserId: req.user.id,
                    UpdateUserId: req.user.id,
                })

                await new_page.save()
                req.user.allow(`page:${new_page.UUID}`)
                await req.user.save()
            }
        }

        /*
         * Call the next function in the stack.
         */
        next()
    }
}

module.exports = exports = GuaranteeRootNode
