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

module.exports = Self => {
    Self.remoteMethodCtx('start', {
        description: 'Starts electronic payment transaction',
        accessType: 'WRITE',
        accepts: [
            {
                arg: 'amount',
                type: 'Number',
                required: true,
            }, {
                arg: 'companyId',
                type: 'Number',
                required: false,
            }, {
                arg: 'urlOk',
                type: 'String',
                required: false,
            }, {
                arg: 'urlKo',
                type: 'String',
                required: false,
            }
        ],
        returns: {
            type: 'Object',
            root: true
        },
        http: {
            path: `/start`,
            verb: 'POST'
        }
    });

    Self.start = async(ctx, amount, companyId, urlOk, urlKo) => {
        const userId = ctx.req.accessToken.userId;
        const [[row]] = await Self.rawSql(
            'CALL hedera.tpvTransaction_start(?, ?, ?)', [
                amount,
                companyId,
                userId
            ], {userId});

        if (!row)
            throw new UserError('Transaction error');

        const orderId = row.transactionId.padStart(12, '0');
        const merchantUrl = row.merchantUrl ? row.merchantUrl : '';
        urlOk = urlOk ? urlOk.replace('_transactionId_', orderId) : '';
        urlKo = urlKo ? urlKo.replace('_transactionId_', orderId) : '';

        const params = {
            'Ds_Merchant_Amount': amount,
            'Ds_Merchant_Order': orderId,
            'Ds_Merchant_MerchantCode': row.merchant,
            'Ds_Merchant_Currency': row.currency,
            'Ds_Merchant_TransactionType': row.transactionType,
            'Ds_Merchant_Terminal': row.terminal,
            'Ds_Merchant_MerchantURL': merchantUrl,
            'Ds_Merchant_UrlOK': urlOk,
            'Ds_Merchant_UrlKO': urlKo
        };
        for (const param in params)
            params[param] = encodeURIComponent(params[param]);

        const json = JSON.stringify(params);
        const merchantParameters = Buffer.from(json).toString('base64');

        const signature = Self.createSignature(
            orderId,
            row.secretKey,
            merchantParameters
        );

        return {
            url: row.url,
            postValues: {
                'Ds_SignatureVersion': 'HMAC_SHA256_V1',
                'Ds_MerchantParameters': merchantParameters,
                'Ds_Signature': signature
            }
        };
    };
};