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

module.exports = Self => {
    Self.remoteMethod('send', {
        description: 'Sends SMS to a destination phone',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'destination',
                type: 'string',
                required: true,
            },
            {
                arg: 'message',
                type: 'string',
                required: true,
            }
        ],
        returns: {
            type: 'object',
            root: true
        },
        http: {
            path: `/send`,
            verb: 'POST'
        }
    });

    Self.send = async(ctx, destination, message) => {
        const userId = ctx.req.accessToken.userId;
        const smsConfig = await Self.app.models.SmsConfig.findOne();

        if (destination.length == 9) {
            const spainPrefix = '0034';
            destination = spainPrefix + destination;
        }

        const params = {
            api_key: smsConfig.apiKey,
            messages: [{
                from: smsConfig.title,
                to: destination,
                text: message
            }]
        };

        let response;
        try {
            if (process.env.NODE_ENV !== 'production')
                response = {result: [{status: 'ok'}]};
            else {
                const jsonTest = {
                    json: params
                };
                response = await got.post(smsConfig.uri, jsonTest).json();
            }
        } catch (e) {
            console.error(e);
        }

        const [result] = response.result;
        const error = result.error_id;

        const newSms = {
            senderFk: userId,
            destination: destination,
            message: message,
            status: error
        };

        const sms = await Self.create(newSms);

        if (error)
            throw new UserError(`We weren't able to send this SMS`);

        return sms;
    };
};