"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const actions_core_1 = require("@segment/actions-core");
const sftp_1 = require("./sftp");
const operations_1 = require("../operations");
const awsClient_1 = require("../awsClient");
const properties_1 = require("../properties");
const action = {
    title: 'Audience Entered (SFTP)',
    description: 'Uploads audience membership data to a file through SFTP for LiveRamp ingestion.',
    defaultSubscription: 'event = "Audience Entered"',
    fields: {
        sftp_username: {
            label: 'Username',
            description: 'User credentials for establishing an SFTP connection with LiveRamp.',
            type: 'string'
        },
        sftp_password: {
            label: 'Password',
            description: 'User credentials for establishing an SFTP connection with LiveRamp.',
            type: 'password'
        },
        sftp_folder_path: {
            label: 'Folder Path',
            description: 'Path within the LiveRamp SFTP server to upload the files to. This path must exist and all subfolders must be pre-created.',
            type: 'string',
            default: { '@template': '/uploads/' },
            format: 'uri-reference'
        },
        audience_key: {
            label: 'LiveRamp Audience Key',
            description: 'Unique ID that identifies members of an audience. A typical audience key might be client customer IDs, email addresses, or phone numbers. See more information on [LiveRamp Audience Key](https://docs.liveramp.com/connect/en/onboarding-terms-and-concepts.html#audience-key)',
            type: 'string',
            required: true,
            default: { '@path': '$.userId' }
        },
        identifier_data: {
            label: 'Identifier Data',
            description: `Additional data pertaining to the user to be written to the file.`,
            type: 'object',
            required: false,
            defaultObjectUI: 'keyvalue:only'
        },
        unhashed_identifier_data: {
            label: 'Hashable Identifier Data',
            description: `Additional data pertaining to the user to be hashed before written to the file. Use field name **phone_number** or **email** to apply LiveRamp's specific hashing rules.`,
            type: 'object',
            required: false,
            defaultObjectUI: 'keyvalue:only'
        },
        delimiter: {
            label: 'Delimeter',
            description: `Character used to separate tokens in the resulting file.`,
            type: 'string',
            required: true,
            default: ','
        },
        filename: {
            label: 'Filename',
            description: `Name of the CSV file to upload for LiveRamp ingestion. For multiple subscriptions, make sure to use a unique filename for each subscription.`,
            type: 'string',
            required: true,
            default: { '@template': '{{properties.audience_key}}_PII.csv' }
        },
        enable_batching: {
            type: 'boolean',
            label: 'Batch data',
            description: 'Receive events in a batch payload. This is required for LiveRamp audiences ingestion.',
            required: true,
            unsafe_hidden: true,
            default: true
        },
        batch_size: {
            label: 'Batch Size',
            description: 'Maximum number of events to include in each batch. Actual batch sizes may be lower.',
            type: 'number',
            required: false,
            unsafe_hidden: true,
            default: 50000
        }
    },
    perform: async (request, { payload, features, rawData, subscriptionMetadata, statsContext }) => {
        return processData({
            request,
            payloads: [payload],
            features,
            rawData: rawData ? [rawData] : [],
            statsContext
        }, subscriptionMetadata);
    },
    performBatch: (request, { payload, features, rawData, subscriptionMetadata, statsContext }) => {
        return processData({
            request,
            payloads: payload,
            features,
            rawData,
            statsContext
        }, subscriptionMetadata);
    }
};
async function processData(input, subscriptionMetadata) {
    (0, operations_1.enrichStatsContextWithMetadata)(input.statsContext, subscriptionMetadata);
    if (input.payloads.length < properties_1.LIVERAMP_MIN_RECORD_COUNT) {
        throw new actions_core_1.PayloadValidationError(`received payload count below LiveRamp's ingestion limits. expected: >=${properties_1.LIVERAMP_MIN_RECORD_COUNT} actual: ${input.payloads.length}`);
    }
    (0, sftp_1.validateSFTP)(input.payloads[0]);
    const { filename, fileContents } = (0, operations_1.generateFile)(input.payloads);
    if (input.features && input.features[properties_1.LIVERAMP_LEGACY_FLOW_FLAG_NAME] === true) {
        const sftpClient = new sftp_1.Client();
        return (0, sftp_1.uploadSFTP)(sftpClient, input.payloads[0], filename, fileContents);
    }
    else {
        return (0, awsClient_1.sendEventToAWS)({
            audienceComputeId: input.rawData?.[0].context?.personas?.computation_id,
            uploadType: 'sftp',
            filename,
            fileContents,
            rowCount: input.payloads.length,
            destinationInstanceID: subscriptionMetadata?.destinationConfigId,
            subscriptionId: subscriptionMetadata?.actionConfigId,
            gzipCompressFile: true,
            sftpInfo: {
                sftpUsername: input.payloads[0].sftp_username,
                sftpPassword: input.payloads[0].sftp_password,
                sftpFolderPath: input.payloads[0].sftp_folder_path
            }
        });
    }
}
exports.default = action;
//# sourceMappingURL=index.js.map