"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 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 ACTION_SLUG = `actions-the-trade-desk-crm`;
const sendEventToAWS = async (request, input) => {
    const uuidValue = (0, uuid_1.v4)();
    const userdataFilePath = `/${ACTION_SLUG}/${input.AdvertiserId}/${input.CrmDataId}/${uuidValue}.txt`;
    const metadataFilePath = `/${ACTION_SLUG}/${input.AdvertiserId}/${input.CrmDataId}/meta.json`;
    const metadata = JSON.stringify({
        TDDAuthToken: input.TDDAuthToken,
        AdvertiserId: input.AdvertiserId,
        CrmDataId: input.CrmDataId,
        DropOptions: input.DropOptions,
        RequeueCount: 0
    });
    const awsCredentials = await (0, sts_1.getAWSCredentialsFromEKS)(request);
    await uploadToAWSS3({
        request,
        bucketName: S3_BUCKET_NAME,
        region: AWS_REGION,
        fileContentType: 'text/plain',
        filePath: userdataFilePath,
        fileContent: input.UsersFormatted,
        awsCredentials: awsCredentials
    });
    return uploadToAWSS3({
        request,
        bucketName: S3_BUCKET_NAME,
        region: AWS_REGION,
        fileContentType: 'application/json',
        filePath: metadataFilePath,
        fileContent: 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