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

module.exports = Self => {
    Self.remoteMethodCtx('addTimeEntry', {
        description: 'Adds a new hour registry',
        accessType: 'WRITE',
        accepts: [{
            arg: 'id',
            type: 'number',
            description: 'The worker id',
            http: {source: 'path'}
        },
        {
            arg: 'timed',
            type: 'date',
            required: true
        },
        {
            arg: 'direction',
            type: 'string',
            required: true
        }],
        returns: [{
            type: 'Object',
            root: true
        }],
        http: {
            path: `/:id/addTimeEntry`,
            verb: 'POST'
        }
    });

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

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

        const isSubordinate = await models.Worker.isSubordinate(ctx, workerId, myOptions);
        const isTeamBoss = await models.Account.hasRole(currentUserId, 'teamBoss', myOptions);
        const isHimself = currentUserId == workerId;

        if (isSubordinate === false || (isSubordinate && isHimself && !isTeamBoss))
            throw new UserError(`You don't have enough privileges`);

        query = `CALL vn.workerTimeControl_clockIn(?,?,?)`;
        const [response] = await Self.rawSql(query, [workerId, args.timed, args.direction], myOptions);
        if (response[0] && response[0].error)
            throw new UserError(response[0].error);

        return response;
    };
};