"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.create_hash = create_hash;
exports.generate_jwt = generate_jwt;
exports.validate_phone = validate_phone;
exports.gen_update_segment_payload = gen_update_segment_payload;
const crypto_1 = require("crypto");
const utils_tax_1 = require("./utils-tax");
const hashing_utils_1 = require("../../lib/hashing-utils");
const versioning_info_1 = require("./versioning-info");
function create_hash(input) {
    if (input === undefined)
        return;
    return (0, hashing_utils_1.processHashing)(input, 'sha256', 'hex', (value) => value.toLowerCase());
}
function generate_jwt(client_id, client_secret) {
    const random_id = (0, utils_tax_1.gen_random_id)(24);
    const current_time = Math.floor(new Date().getTime() / 1000);
    const url = `https://id.b2b.yahooincapis.com/zts/${versioning_info_1.YAHOO_AUDIENCES_TAXONOMY_API_VERSION}`;
    const jwt_payload = {
        iss: client_id,
        sub: client_id,
        aud: url,
        jti: random_id,
        exp: current_time + 3600,
        iat: current_time
    };
    const jwt_header = {
        alg: 'HS256',
        typ: 'JWT'
    };
    const jwt_header_encoded = Buffer.from(JSON.stringify(jwt_header)).toString('base64');
    const jwt_payload_encoded = Buffer.from(JSON.stringify(jwt_payload)).toString('base64');
    const jwt_head_payload = jwt_header_encoded + '.' + jwt_payload_encoded;
    const hash = (0, crypto_1.createHmac)('sha256', client_secret);
    const signature = hash.update(jwt_head_payload).digest('base64');
    const jwt = jwt_head_payload + '.' + signature;
    return jwt;
}
function validate_phone(phone) {
    const phone_num = phone.replace(/\D/g, '');
    if (phone_num.length <= 15 && phone_num.length >= 1) {
        return '+' + phone_num;
    }
    else {
        return '';
    }
}
function gen_update_segment_payload(payloads) {
    const data_groups = {};
    const data = [];
    for (const event of payloads) {
        let hashed_email = '';
        if (event.email) {
            hashed_email = create_hash(event.email.toLowerCase());
        }
        let idfa = '';
        let gpsaid = '';
        if (event.advertising_id) {
            if (event.device_type) {
                switch (event.device_type) {
                    case 'ios':
                        idfa = event.advertising_id;
                        break;
                    case 'android':
                        gpsaid = event.advertising_id;
                        break;
                }
            }
            else {
                if (event.advertising_id === event.advertising_id.toUpperCase()) {
                    idfa = event.advertising_id;
                }
                else {
                    gpsaid = event.advertising_id;
                }
            }
        }
        let hashed_phone = '';
        if (event.phone) {
            const phone = validate_phone(event.phone);
            if (phone !== '') {
                hashed_phone = create_hash(phone);
            }
        }
        if (hashed_email === '' && idfa === '' && gpsaid === '' && hashed_phone === '') {
            continue;
        }
        const ts = Math.floor(new Date().getTime() / 1000);
        const seg_key = event.segment_audience_key;
        let exp;
        if (event.event_attributes[seg_key] === true) {
            exp = ts + 90 * 24 * 60 * 60;
        }
        if (event.event_attributes[seg_key] === false) {
            exp = 0;
        }
        const seg_id = event.segment_audience_id;
        const group_key = `${hashed_email}|${idfa}|${gpsaid}|${hashed_phone}`;
        if (!(group_key in data_groups)) {
            data_groups[group_key] = [];
        }
        data_groups[group_key].push({
            exp: String(exp),
            seg_id: seg_id,
            ts: String(ts)
        });
    }
    for (const [key, grouped_values] of Object.entries(data_groups)) {
        const [hashed_email, idfa, gpsaid, hashed_phone] = key.split('|');
        let action_string = '';
        for (const values of grouped_values) {
            action_string += 'exp=' + values.exp + '&seg_id=' + values.seg_id + '&ts=' + values.ts + ';';
        }
        action_string = action_string.slice(0, -1);
        data.push([hashed_email, idfa, gpsaid, hashed_phone, action_string]);
    }
    const gdpr_flag = payloads[0].gdpr_settings ? payloads[0].gdpr_settings.gdpr_flag : false;
    const yahoo_payload = {
        schema: ['SHA256EMAIL', 'IDFA', 'GPADVID', 'HASHEDID', 'SEGMENTS'],
        data: data,
        gdpr: gdpr_flag
    };
    if (gdpr_flag) {
        yahoo_payload.gdpr_euconsent = payloads[0].gdpr_settings?.gdpr_euconsent;
    }
    return yahoo_payload;
}
//# sourceMappingURL=utils-rt.js.map