module.exports = Self => {
    Self.remoteMethodCtx('send', {
        description: 'Send message to user',
        accessType: 'WRITE',
        accepts: [{
            arg: 'data',
            type: 'object',
            required: true,
            description: 'recipientFk, message',
            http: {source: 'body'}
        }, {
            arg: 'context',
            type: 'object',
            http: function(ctx) {
                return ctx;
            }
        }],
        returns: {
            type: 'boolean',
            root: true
        },
        http: {
            path: `/:recipient/send`,
            verb: 'post'
        }
    });

    Self.send = async(ctx, data, transaction) => {
        const accessToken = ctx.options && ctx.options.accessToken || ctx.req && ctx.req.accessToken;
        const userId = accessToken.userId;
        const models = Self.app.models;
        const sender = await models.Account.findById(userId, transaction);
        const recipient = await models.Account.findById(data.recipientFk, transaction);

        await Self.create({
            sender: sender.name,
            recipient: recipient.name,
            message: data.message
        }, transaction);

        return await models.MessageInbox.create({
            sender: sender.name,
            recipient: recipient.name,
            finalRecipient: recipient.name,
            message: data.message
        }, transaction);
    };
};