const UserError = require('vn-loopback/util/user-error');

module.exports = Self => {
    Self.execute = async(ctx, type, query, params, options) => {
        const userId = ctx.req.accessToken.userId;
        const models = Self.app.models;
        params = params ?? [];

        const myOptions = {userId: ctx.req.accessToken.userId};
        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const chain = query.split(' ')[1];

        const [canExecute] = await models.ProcsPriv.rawSql(
            'SELECT account.user_hasRoutinePriv(?,?,?)',
            [type, chain, userId],
            myOptions);

        if (!Object.values(canExecute)[0]) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED');

        const argString = params.map(() => '?').join(',');

        const response = await models.ProcsPriv.rawSql(query + `(${argString})`, params, myOptions);
        if (!Array.isArray(response)) return;
        return response[0];
    };
};