module.exports = Self => {
    Self.remoteMethodCtx('usesMana', {
        description: 'Returns if the worker uses mana',
        accessType: 'READ',
        accepts: [],
        returns: {
            type: 'boolean',
            root: true
        },
        http: {
            path: `/usesMana`,
            verb: 'GET'
        }
    });

    Self.usesMana = async(ctx, options) => {
        const models = Self.app.models;
        const userId = ctx.req.accessToken.userId;
        const myOptions = {};

        if (typeof options == 'object')
            Object.assign(myOptions, options);

        const isManaExcluded = await models.WorkerManaExcluded.findById(userId, null, myOptions);
        if (isManaExcluded) return false;

        const salesDepartment = await models.Department.findOne({where: {code: 'VT'}, fields: 'id'}, myOptions);
        const departments = await models.Department.getLeaves(ctx, salesDepartment.id, null, myOptions);
        const workerDepartment = await models.WorkerDepartment.findById(userId, null, myOptions);
        if (!workerDepartment) return false;

        const usesMana = departments.find(department => department.id == workerDepartment.departmentFk);

        return !!usesMana;
    };
};