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

module.exports = Self => {
    Self.remoteMethodCtx('addTime', {
        description: 'Adds a new hour registry',
        accessType: 'WRITE',
        accepts: [{
            arg: 'data',
            type: 'object',
            required: true,
            description: 'workerFk, timed',
            http: {source: 'body'}
        }],
        returns: [{
            type: 'Object',
            root: true
        }],
        http: {
            path: `/addTime`,
            verb: 'POST'
        }
    });

    Self.addTime = async(ctx, data) => {
        const Worker = Self.app.models.Worker;
        const myUserId = ctx.req.accessToken.userId;
        const myWorker = await Worker.findOne({where: {userFk: myUserId}});
        const isSubordinate = await Worker.isSubordinate(ctx, data.workerFk);
        const isTeamBoss = await Self.app.models.Account.hasRole(myUserId, 'teamBoss');

        if (isSubordinate === false || (isSubordinate && myWorker.id == data.workerFk && !isTeamBoss))
            throw new UserError(`You don't have enough privileges`);

        const subordinate = await Worker.findById(data.workerFk);

        return Self.create({
            userFk: subordinate.userFk,
            timed: data.timed,
            manual: 1
        });
    };
};