"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldSendToStudio = exports.fetchProfileExternalIds = exports.getToAddressField = exports.DEFAULT_COOLING_OFF_PERIOD = exports.PROFILE_API_BASE_URL = exports.STUDIO_BASE_URL = void 0;
const actions_core_1 = require("@segment/actions-core");
exports.STUDIO_BASE_URL = 'https://studio.twilio.com';
exports.PROFILE_API_BASE_URL = 'https://profiles.segment.com';
exports.DEFAULT_COOLING_OFF_PERIOD = 60;
const getToAddressField = async (request, settings, payload) => {
    const externalIds = await (0, exports.fetchProfileExternalIds)(request, settings, payload.userId, payload.anonymousId);
    if (externalIds.length <= 0) {
        return false;
    }
    const latestId = externalIds.reduce((acc, current) => {
        return new Date(acc.created_at) > new Date(current.created_at) ? acc : current;
    });
    return latestId?.id;
};
exports.getToAddressField = getToAddressField;
const fetchProfileExternalIds = async (request, settings, userId, anonymousId) => {
    try {
        const identifier = userId ? `user_id:${userId}` : `anonymous_id:${anonymousId}`;
        const response = await request(`${exports.PROFILE_API_BASE_URL}/v1/spaces/${settings.spaceId}/collections/users/profiles/${identifier}/external_ids?include=phone`, {
            headers: {
                authorization: `Basic ${Buffer.from(settings.profileApiAccessToken + ':').toString('base64')}`,
                'content-type': 'application/json'
            }
        });
        const body = await response.json();
        return body.data;
    }
    catch (error) {
        throw new actions_core_1.IntegrationError('Unable to trigger Studio Flow. Fetching phone external Id failed.', 'Profile fetch API failure', 500);
    }
};
exports.fetchProfileExternalIds = fetchProfileExternalIds;
const shouldSendToStudio = (cacheKey, stateContext, coolingOffPeriod) => {
    if (stateContext?.getRequestContext?.(cacheKey))
        return false;
    stateContext?.setResponseContext?.(cacheKey, cacheKey, { second: coolingOffPeriod || exports.DEFAULT_COOLING_OFF_PERIOD });
    return true;
};
exports.shouldSendToStudio = shouldSendToStudio;
//# sourceMappingURL=utils.js.map