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

/*
 * PageRoute Middleware
 * -------------------------------------------------------------
 * Put some description here!
 */
class PageRoute 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')
        const PageId = req.form.PageId ? req.form.PageId : req.params.PageId
        if ( !PageId ) return res.status(400).message(`Missing PageId.`).api({})

        const level = args.level ? args.level : 'view'
        const page = await Page.findOne({UUID: PageId})

        if ( !page ) return res.status(404).message(`Unable to find page with that id.`).api({})
        if ( !(await page.is_accessible_by(req.user, level)) ) return req.security.deny()

        if ( !req.form ) req.form = {}
        req.form.page = page

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

module.exports = exports = PageRoute
