"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAudienceRequest = exports.createAudienceRequest = exports.FLAGON_NAME = exports.CANARY_API_VERSION = exports.API_VERSION = void 0;
exports.getApiVersion = getApiVersion;
exports.editDeviceMobileIds = editDeviceMobileIds;
exports.editContactInfo = editContactInfo;
const actions_core_1 = require("@segment/actions-core");
const hashing_utils_1 = require("../../lib/hashing-utils");
const versioning_info_1 = require("./versioning-info");
exports.API_VERSION = versioning_info_1.FIRST_PARTY_DV360_API_VERSION;
exports.CANARY_API_VERSION = versioning_info_1.FIRST_PARTY_DV360_CANARY_API_VERSION;
exports.FLAGON_NAME = 'first-party-dv360-canary-version';
const DV360API = `https://displayvideo.googleapis.com/`;
const CONSENT_STATUS_GRANTED = 'CONSENT_STATUS_GRANTED';
function getApiVersion(features, statsContext) {
    const statsClient = statsContext?.statsClient;
    const tags = statsContext?.tags;
    const version = features && features[exports.FLAGON_NAME] ? exports.CANARY_API_VERSION : exports.API_VERSION;
    statsClient?.incr('dv360_api_version', 1, [...(tags || []), `version:${version}`]);
    return version;
}
function getAudienceEndpoint(version, advertiserId, audienceId) {
    if (audienceId) {
        return DV360API + `${version}/firstPartyAndPartnerAudiences/` + `${audienceId}?advertiserId=${advertiserId}`;
    }
    else {
        return DV360API + `${version}/firstPartyAndPartnerAudiences` + `?advertiserId=${advertiserId}`;
    }
}
function getEditCustomerMatchMembersEndpoint(version, audienceId) {
    return DV360API + `${version}/firstPartyAndPartnerAudiences/` + audienceId + ':editCustomerMatchMembers';
}
const createAudienceRequest = (request, params) => {
    const { advertiserId, audienceName, description, membershipDurationDays, audienceType, appId, token, features, statsContext } = params;
    const version = getApiVersion(features, statsContext);
    const endpoint = getAudienceEndpoint(version, advertiserId);
    return request(endpoint, {
        method: 'POST',
        headers: {
            authorization: `Bearer ${token}`,
            'Content-Type': 'application/json; charset=utf-8'
        },
        json: {
            displayName: audienceName,
            audienceType: audienceType,
            membershipDurationDays: membershipDurationDays,
            description: description,
            audienceSource: 'AUDIENCE_SOURCE_UNSPECIFIED',
            firstPartyAndPartnerAudienceType: 'TYPE_FIRST_PARTY',
            appId: appId
        }
    });
};
exports.createAudienceRequest = createAudienceRequest;
const getAudienceRequest = (request, params) => {
    const { advertiserId, audienceId, token, features, statsContext } = params;
    const version = getApiVersion(features, statsContext);
    const endpoint = getAudienceEndpoint(version, advertiserId, audienceId);
    return request(endpoint, {
        method: 'GET',
        headers: {
            authorization: `Bearer ${token}`,
            'Content-Type': 'application/json; charset=utf-8'
        }
    });
};
exports.getAudienceRequest = getAudienceRequest;
async function editDeviceMobileIds(request, payloads, operation, statsContext, features) {
    const { external_id: audienceId, advertiser_id: advertiserId } = payloads[0];
    const allMobileDeviceIds = payloads.flatMap((p) => Array.isArray(p.mobileDeviceIds) ? p.mobileDeviceIds : [p.mobileDeviceIds]);
    const version = getApiVersion(features, statsContext);
    const endpoint = getEditCustomerMatchMembersEndpoint(version, audienceId);
    const mobileDeviceIdList = {
        mobileDeviceIds: allMobileDeviceIds,
        consent: {
            adUserData: CONSENT_STATUS_GRANTED,
            adPersonalization: CONSENT_STATUS_GRANTED
        }
    };
    const requestPayload = JSON.stringify({
        advertiserId: advertiserId,
        ...(operation === 'add' ? { addedMobileDeviceIdList: mobileDeviceIdList } : {}),
        ...(operation === 'remove' ? { removedMobileDeviceIdList: mobileDeviceIdList } : {})
    });
    const response = await request(endpoint, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: requestPayload
    });
    const responseAudienceId = response.data.firstPartyAndPartnerAudienceId;
    if (!response.data || !responseAudienceId) {
        statsContext?.statsClient?.incr('addCustomerMatchMembers.error', allMobileDeviceIds.length, statsContext?.tags);
        throw new actions_core_1.IntegrationError(`API returned error: ${response.data?.error || 'Unknown error'}`, 'API_REQUEST_ERROR', 400);
    }
    statsContext?.statsClient?.incr('addCustomerMatchMembers.success', allMobileDeviceIds.length, statsContext?.tags);
    return response.data;
}
function buildContactInfoList(contactInfos) {
    return {
        contactInfos,
        consent: {
            adUserData: CONSENT_STATUS_GRANTED,
            adPersonalization: CONSENT_STATUS_GRANTED
        }
    };
}
function buildRequestPayload(advertiserId, contactInfoList, operation) {
    return JSON.stringify({
        advertiserId,
        ...(operation === 'add' ? { addedContactInfoList: contactInfoList } : {}),
        ...(operation === 'remove' ? { removedContactInfoList: contactInfoList } : {})
    });
}
async function editContactInfo(request, payloads, operation, statsContext, features) {
    if (!payloads || payloads.length === 0)
        return;
    const validPayloads = payloads.filter((payload) => payload.emails !== undefined ||
        payload.phoneNumbers !== undefined ||
        payload.firstName !== undefined ||
        payload.lastName !== undefined);
    if (validPayloads.length === 0)
        return;
    const { external_id: audienceId, advertiser_id: advertiserId } = validPayloads[0];
    if (!audienceId || !advertiserId) {
        throw new actions_core_1.IntegrationError('Missing required audience or advertiser ID', 'MISSING_REQUIRED_FIELD', 400);
    }
    const contactInfos = validPayloads.map(processPayload);
    const contactInfoList = buildContactInfoList(contactInfos);
    const requestPayload = buildRequestPayload(advertiserId, contactInfoList, operation);
    const version = getApiVersion(features, statsContext);
    const endpoint = getEditCustomerMatchMembersEndpoint(version, audienceId);
    const response = await request(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json; charset=utf-8' },
        body: requestPayload
    });
    statsContext?.statsClient?.incr('addCustomerMatchMembers.success', contactInfos.length, statsContext?.tags);
    return response.data;
}
function normalizeAndHash(data) {
    const normalizedData = data.toLowerCase().trim();
    return (0, hashing_utils_1.processHashing)(normalizedData, 'sha256', 'hex');
}
function processPayload(payload) {
    const result = {};
    if (payload.emails) {
        result.hashedEmails = normalizeAndHash(payload.emails);
    }
    if (payload.phoneNumbers) {
        result.hashedPhoneNumbers = normalizeAndHash(payload.phoneNumbers);
    }
    if (payload.zipCodes) {
        result.zipCodes = payload.zipCodes;
    }
    if (payload.firstName) {
        result.hashedFirstName = normalizeAndHash(payload.firstName);
    }
    if (payload.lastName) {
        result.hashedLastName = normalizeAndHash(payload.lastName);
    }
    if (payload.countryCode) {
        result.countryCode = payload.countryCode;
    }
    return result;
}
//# sourceMappingURL=functions.js.map