module.exports = Self => {
    Self.remoteMethodCtx('sendCheckingPresence', {
        description: 'Sends a RocketChat message to a working worker or department channel',
        accessType: 'WRITE',
        accepts: [{
            arg: 'workerId',
            type: 'Number',
            required: true,
            description: 'The worker id of the destinatary'
        },
        {
            arg: 'message',
            type: 'String',
            required: true,
            description: 'The message'
        }],
        returns: {
            type: 'Object',
            root: true
        },
        http: {
            path: `/sendCheckingPresence`,
            verb: 'POST'
        }
    });

    Self.sendCheckingPresence = async(ctx, recipientId, message) => {
        if (!recipientId) return false;

        const models = Self.app.models;
        const account = await models.Account.findById(recipientId);
        const userId = ctx.req.accessToken.userId;

        if (recipientId == userId) return false;

        if (!account)
            throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`);

        const query = `SELECT worker_isWorking(?) isWorking`;
        const [result] = await Self.rawSql(query, [recipientId]);

        if (!result.isWorking) {
            const workerDepartment = await models.WorkerDepartment.findById(recipientId, {
                include: {
                    relation: 'department'
                }
            });
            const department = workerDepartment && workerDepartment.department();
            const channelName = department && department.chatName;

            if (channelName)
                return Self.send(ctx, `#${channelName}`, `@${account.name} ➔ ${message}`);
        }

        return Self.send(ctx, `@${account.name}`, message);
    };
};