const fs = require('fs');
const path = require('path');
const envfile = require('envfile');
const crypto = require('crypto');
const log = require('loglevel');

class KmsProxyServ {
    constructor () {
        this.axios = global.axiosInstances.axiosAfcInstance;
    }

    authenticateSam = async (samId) => {
        try {
            const res = await this.axios.post('kms-proxy/v2/'+process.env.CLIENT_DEVICE_MNEMONIC+'/'+process.env.POS_DEVICE_ID+'/sam/'+samId+'/authentication', {});
            if (res.errors) { return null; }
            if (res.status == 500) { return (process.env.CLIENT_SAM_KEY != '') ? process.env.CLIENT_SAM_KEY : null; }
            if (process.env.POS_DEVELOPMENT_MODE == 'true') {
                log.info('hostAuthKey', res.hostAuthKey);
                log.info('salt', res.salt);
                log.info('decrypt', await this.decryptResponse(res));
                return res;
            }
            // update config file for fallback
            if (process.env.CLIENT_SAM_KEY == '') {
                let configFile = envfile.parse(fs.readFileSync(path.join(process.cwd(), 'configs', '.env')));
                if (configFile.CLIENT_SAM_KEY == '') {
                    configFile.CLIENT_SAM_KEY = await this.decryptResponse(res);
                    fs.writeFileSync(path.join(process.cwd(), 'configs', '.env'), envfile.stringify(configFile));
                }
            }
            return res;
        } catch (err) {
            log.error(err);
        }
    }

    decryptResponse = async (response) => {
        try {
            const hostAuthKey = new Buffer.from(response.hostAuthKey, 'hex');
            const salt = new Buffer.from(response.salt, 'hex');
            const terminalId = global.currentPosData.terminalId.toString();

            const secret = crypto.pbkdf2Sync(terminalId, salt, 65536, response.salt.length, 'sha256');
            const iv = new Buffer.from(new Buffer.concat([salt, salt]));

            const decipher = crypto.createDecipheriv('aes-128-cbc', secret, iv);
            let decrypted = decipher.update(hostAuthKey, 'binary', 'hex') + decipher.final('hex');

            return decrypted.toUpperCase();
        } catch (err) {
            log.error('Cannot decrypt response', err);
        }
    }

}

module.exports = KmsProxyServ;
