"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendEventToAWS = void 0;
const uuid_1 = require("@lukeed/uuid");
const aws4_1 = __importDefault(require("aws4"));
const actions_core_1 = require("@segment/actions-core");
const sts_1 = require("../../lib/AWS/sts");
const properties_1 = require("./properties");
const NODE_ENV = process.env['NODE_ENV'] || `stage`;
const AWS_REGION = process.env['AWS_REGION'] || `us-west-2`;
const S3_BUCKET_NAME = `integrations-outbound-event-store-${NODE_ENV}-${AWS_REGION}`;
const sendEventToAWS = async (request, input) => {
    const uuidValue = (0, uuid_1.v4)();
    const aggreagtedFilePath = `${input.destinationInstanceID ?? ''}${input.subscriptionId ? '/' + input.subscriptionId : ''}${input.audienceComputeId ? '/' + input.audienceComputeId : ''}`.replace(/^\/+|\/+$/g, '') || '';
    const userdataFilePath = `/${properties_1.ACTION_SLUG}/${aggreagtedFilePath}/${uuidValue}.csv`;
    const metadataFilePath = `/${properties_1.ACTION_SLUG}/${aggreagtedFilePath}/meta.json`;
    const metadata = {
        audienceKey: input.audienceComputeId || '',
        uploadType: input.uploadType,
        filename: input.filename,
        gzipCompressFile: input.gzipCompressFile
    };
    if (input.uploadType === 'sftp') {
        metadata.sftpInfo = {
            sftpHost: properties_1.LIVERAMP_SFTP_SERVER,
            sftpPort: properties_1.LIVERAMP_SFTP_PORT,
            sftpUsername: input.sftpInfo?.sftpUsername || '',
            sftpPassword: input.sftpInfo?.sftpPassword || '',
            sftpFolderPath: input.sftpInfo?.sftpFolderPath || ''
        };
    }
    else {
        metadata.s3Info = {
            s3BucketName: input.s3Info?.s3BucketName || '',
            s3Region: input.s3Info?.s3Region || '',
            s3AccessKeyId: input.s3Info?.s3AccessKeyId || '',
            s3SecretAccessKey: input.s3Info?.s3SecretAccessKey || '',
            s3BucketPath: input.s3Info?.s3BucketPath || ''
        };
    }
    const awsCredentials = await (0, sts_1.getAWSCredentialsFromEKS)(request);
    await uploadToAWSS3({
        request,
        bucketName: S3_BUCKET_NAME,
        region: AWS_REGION,
        fileContentType: 'text/csv',
        filePath: userdataFilePath,
        fileContent: input.fileContents,
        awsCredentials: awsCredentials
    });
    return uploadToAWSS3({
        request,
        bucketName: S3_BUCKET_NAME,
        region: AWS_REGION,
        fileContentType: 'application/json',
        filePath: metadataFilePath,
        fileContent: JSON.stringify(metadata),
        awsCredentials: awsCredentials
    });
};
exports.sendEventToAWS = sendEventToAWS;
async function uploadToAWSS3(input) {
    const s3UploadRequest = aws4_1.default.sign({
        host: `${input.bucketName}.s3.${input.region}.amazonaws.com`,
        path: input.filePath,
        body: input.fileContent,
        method: 'PUT',
        service: 's3',
        region: input.region,
        headers: {
            'Content-Type': input.fileContentType,
            Accept: 'application/json'
        }
    }, {
        accessKeyId: input.awsCredentials.accessKeyId,
        secretAccessKey: input.awsCredentials.secretAccessKey,
        sessionToken: input.awsCredentials.sessionToken
    });
    if (!s3UploadRequest.headers || !s3UploadRequest.method || !s3UploadRequest.host || !s3UploadRequest.path) {
        throw new actions_core_1.InvalidAuthenticationError('Unable to generate signature header for AWS S3 request.');
    }
    return input.request(`https://${input.bucketName}.s3.${input.region}.amazonaws.com${input.filePath}`, {
        method: 'PUT',
        body: s3UploadRequest.body,
        headers: s3UploadRequest.headers
    });
}
//# sourceMappingURL=awsClient.js.map