/*!
 * Copyright (C) Microsoft Corporation. All rights reserved.
 */
import { AppInsightsCore, } from '@microsoft/1ds-core-js';
import { PostChannel } from '@microsoft/1ds-post-js';
/** 1DS Aria project IDs shared by the webplayer and CLI. */
const AriaProjectIds = {
    Production: '5c3a61f48d7c4522912765ae7465ab5c-fb3d6606-fe59-4d6b-9bb1-5e993d889672-7138',
    NonProduction: '3fb21f3df5c44380bf452fd710f4d50c-0e3f82aa-6d27-41d8-b727-c96b28f99992-7504',
    Mooncake: '1c1d139788f74386bd95e752dd781371-04b4424b-e5c1-46ae-8312-28e9fa5832c0-6923',
    GccModerate: '0d7685a948a140789ac92933d3dc2d87-2dd0c1ce-8f10-41f0-a70a-2f9e51a851c8-6823',
    GccHigh: 'd31229fb23b0406790b9332e5f465dfc-a6b19a0e-170d-4570-bda5-f35e3668e162-7067',
    DoD: '41cc10dad35043adbcdace2896484ab4-5ebbc1d6-04c9-486d-a6b6-e5963cd778da-7542',
};
/**
 * Default property-to-column promotion map matching the webplayer convention.
 * Properties matching these keys are promoted to top-level data columns;
 * the rest go into the customDimensions JSON blob.
 */
const DefaultPropertyToColumn = {
    apiId: 'apiId',
    appSequenceNumber: 'appSequenceNumber',
    duration: 'duration',
    environmentId: 'environmentId',
    httpMethod: 'httpMethod',
    httpStatus: 'httpStatus',
    operationName: 'operation_Name',
    playerAppId: 'playerAppId',
    scenarioGuid: 'scenarioGuid',
    scenarioName: 'scenarioName',
    scenarioResult: 'scenarioResult',
    serverLocation: 'serverLocation',
    url: 'url',
    webPlayerUrl: 'webPlayerUrl',
};
function resolveInstrumentationKey(clusterCategory) {
    switch (clusterCategory) {
        case 'prod':
        case 'firstrelease':
        case 'ex':
        case 'rx':
            return AriaProjectIds.Production;
        case 'mooncake':
            return AriaProjectIds.Mooncake;
        case 'gov':
            return AriaProjectIds.GccModerate;
        case 'high':
            return AriaProjectIds.GccHigh;
        case 'dod':
            return AriaProjectIds.DoD;
        default:
            return AriaProjectIds.NonProduction;
    }
}
function resolveCollectorUrl(clusterCategory, telemetryLocation = 'global') {
    switch (clusterCategory) {
        case 'mooncake':
            return 'https://collector.azure.cn/OneCollector/1.0/';
        case 'gov':
        case 'high':
            return 'https://tb.events.data.microsoft.com/OneCollector/1.0/';
        case 'dod':
            return 'https://pf.events.data.microsoft.com/OneCollector/1.0/';
        case 'ex':
            return 'https://collector.azure.eaglex.ic.gov/OneCollector/1.0/';
        case 'rx':
            return 'https://collector.azure.microsoft.scloud/OneCollector/1.0/';
        default:
            if (telemetryLocation === 'eu') {
                return 'https://eu-mobile.events.data.microsoft.com/OneCollector/1.0/';
            }
            return 'https://us-mobile.events.data.microsoft.com/OneCollector/1.0/';
    }
}
function resolveAppName(clusterCategory) {
    switch (clusterCategory) {
        case 'local':
        case 'dev':
        case 'test':
        case 'preprod':
            return 'powerappsclientnonprod';
        default:
            return 'powerappsclient';
    }
}
export class OneDsTelemetryProvider {
    appName;
    clientType;
    clusterCategory;
    core;
    defaultProperties = {};
    propertyColumnMap;
    minSeverity;
    _sessionId;
    userIdentity;
    constructor(config) {
        this._sessionId = crypto.randomUUID();
        this.appName = resolveAppName(config.clusterCategory);
        this.clientType = config.clientType;
        this.clusterCategory = config.clusterCategory;
        this.minSeverity = config.minSeverity ?? 'info';
        // Merge default promotion map with consumer overrides (overrides win)
        this.propertyColumnMap = { ...DefaultPropertyToColumn, ...config.propertyColumnMap };
        if (config.commonProperties) {
            Object.assign(this.defaultProperties, config.commonProperties);
        }
        const postChannel = new PostChannel();
        const instrumentationKey = config.instrumentationKey ?? resolveInstrumentationKey(config.clusterCategory);
        const collectorUrl = resolveCollectorUrl(config.clusterCategory, config.telemetryLocation);
        const coreConfig = {
            instrumentationKey,
            channels: [[postChannel]],
            endpointUrl: collectorUrl,
        };
        if (config.channelConfig) {
            coreConfig.extensionConfig = {
                [postChannel.identifier]: config.channelConfig,
            };
        }
        this.core = new AppInsightsCore();
        this.core.initialize(coreConfig, []);
        // Request IP masking — the 1DS collector attaches client IP by default;
        // HASH_IDENTIFIERS_FLAG (0x100000) tells it to mask/hash the IP server-side.
        this.core.addTelemetryInitializer((envelope) => {
            const ext = (envelope.ext = envelope.ext ?? {});
            const utc = (ext.utc = ext.utc ?? {});
            utc.eventFlags = (utc.eventFlags || 0) | 0x100000;
        });
    }
    /**
     * Register a telemetry initializer that runs on every envelope before send.
     * Use this to add Part A Common Schema extensions (ext.app, ext.web, ext.os, etc.)
     * that require platform-specific APIs (e.g. browser info, OS info).
     */
    addTelemetryInitializer(initializer) {
        this.core.addTelemetryInitializer(initializer);
    }
    track(event) {
        const allProperties = {
            ...this.defaultProperties,
            ...event.properties,
        };
        // Build data object with fixed columns matching webplayer convention
        const data = {
            app_Name: this.appName,
            clientType: this.clientType,
            clusterCategory: this.clusterCategory,
            device_Id: 'browser',
            event_Name: event.eventName,
            sequenceNumber: event.sequenceNumber,
            session_Id: this._sessionId,
            severity: event.severity,
            timestamp: event.timestamp,
        };
        // User identity promoted to top-level columns directly
        if (this.userIdentity) {
            data.objectId = this.userIdentity.objectId;
            data.tenantId = this.userIdentity.tenantId;
        }
        if (event.duration !== undefined) {
            data.duration = event.duration;
        }
        // Promote properties matching the column map to top-level data fields
        // Properties are kept in allProperties so they also appear in customDimensions
        for (const [propKey, columnName] of Object.entries(this.propertyColumnMap)) {
            if (propKey in allProperties) {
                data[columnName] = allProperties[propKey];
            }
        }
        // Serialize remaining properties as customDimensions
        data.customDimensions = JSON.stringify(allProperties);
        const item = {
            name: 'event',
            time: event.timestamp,
            baseType: 'custom',
            data,
        };
        this.core.track(item);
    }
    flush() {
        return new Promise((resolve) => {
            this.core.flush(true, () => {
                resolve();
            });
        });
    }
    teardown() {
        return new Promise((resolve) => {
            this.core.unload(true, () => {
                resolve();
            });
        });
    }
    get sessionId() {
        return this._sessionId;
    }
    set sessionId(value) {
        this._sessionId = value;
    }
    identifyUser(identity) {
        this.userIdentity = identity;
    }
    setDefaultProperty(name, value) {
        this.defaultProperties[name] = value;
    }
}
//# sourceMappingURL=OneDsTelemetryProvider.js.map