"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Client = void 0;
exports.validateSFTP = validateSFTP;
exports.uploadSFTP = uploadSFTP;
exports.doSFTP = doSFTP;
exports.testAuthenticationSFTP = testAuthenticationSFTP;
const actions_core_1 = require("@segment/actions-core");
const ssh2_sftp_client_1 = __importDefault(require("ssh2-sftp-client"));
exports.Client = ssh2_sftp_client_1.default;
const path_1 = __importDefault(require("path"));
const properties_1 = require("../properties");
var SFTPErrorCode;
(function (SFTPErrorCode) {
    SFTPErrorCode[SFTPErrorCode["NO_SUCH_FILE"] = 2] = "NO_SUCH_FILE";
})(SFTPErrorCode || (SFTPErrorCode = {}));
function validateSFTP(payload) {
    if (!payload.sftp_username) {
        throw new actions_core_1.InvalidAuthenticationError('Selected SFTP upload mode, but missing credentials (Username)');
    }
    if (!payload.sftp_password) {
        throw new actions_core_1.InvalidAuthenticationError('Selected SFTP upload mode, but missing credentials (Password)');
    }
    if (!payload.sftp_folder_path) {
        throw new actions_core_1.InvalidAuthenticationError('Selected SFTP upload mode, but missing SFTP folder path.');
    }
}
async function uploadSFTP(sftp, payload, filename, fileContent) {
    return doSFTP(sftp, payload, async (sftp) => {
        const targetPath = path_1.default.join(payload.sftp_folder_path, filename);
        return sftp.put(fileContent, targetPath);
    });
}
async function doSFTP(sftp, payload, action) {
    await sftp.connect({
        host: properties_1.LIVERAMP_SFTP_SERVER,
        port: properties_1.LIVERAMP_SFTP_PORT,
        username: payload.sftp_username,
        password: payload.sftp_password
    });
    let timeoutError;
    const timeout = setTimeout(() => {
        void sftp.end().catch((err) => {
            console.error(err);
        });
        timeoutError = new actions_core_1.SelfTimeoutError(`did not complete SFTP operation under allotted time: ${actions_core_1.DEFAULT_REQUEST_TIMEOUT}`);
    }, actions_core_1.DEFAULT_REQUEST_TIMEOUT);
    let retVal;
    try {
        retVal = await action(sftp);
        if (timeoutError)
            throw timeoutError;
    }
    catch (e) {
        const sftpError = e;
        if (sftpError) {
            if (sftpError.code == SFTPErrorCode.NO_SUCH_FILE) {
                throw new actions_core_1.PayloadValidationError(`Could not find path: ${payload.sftp_folder_path}`);
            }
        }
        throw e;
    }
    finally {
        clearTimeout(timeout);
        if (!timeoutError) {
            await sftp.end();
        }
    }
    return retVal;
}
async function testAuthenticationSFTP(sftp, payload) {
    return doSFTP(sftp, payload, async (sftp) => {
        return sftp.exists(payload.sftp_folder_path).then((fileType) => {
            if (!fileType)
                throw new actions_core_1.PayloadValidationError(`Could not find path: ${payload.sftp_folder_path}`);
        });
    });
}
//# sourceMappingURL=sftp.js.map