import { CoveoInsightClient, } from "coveo.analytics/dist/browser.mjs";
import { buildFacetStateMetadata, getStateNeededForFacetMetadata, } from '../../features/facets/facet-set/facet-set-analytics-actions-utils.js';
import { getQueryInitialState } from '../../features/query/query-state.js';
import { getSearchInitialState } from '../../features/search/search-state.js';
import { getOrganizationEndpoint } from '../platform-client.js';
import { BaseAnalyticsProvider } from './base-analytics.js';
import { wrapAnalyticsClientSendEventHook, wrapPreprocessRequest, } from './coveo-analytics-utils.js';
export class InsightAnalyticsProvider extends BaseAnalyticsProvider {
    getSearchUID() {
        const newState = this.getState();
        return (newState.search?.searchResponseId ||
            newState.search?.response.searchUid ||
            getSearchInitialState().response.searchUid);
    }
    getPipeline() {
        return (this.state.pipeline || this.state.search?.response.pipeline || 'default');
    }
    getSearchEventRequestPayload() {
        return {
            queryText: this.queryText,
            responseTime: this.responseTime,
            results: this.mapResultsToAnalyticsDocument(),
            numberOfResults: this.numberOfResults,
        };
    }
    getFacetState() {
        return buildFacetStateMetadata(getStateNeededForFacetMetadata(this.state));
    }
    getBaseMetadata() {
        const state = this.getState();
        const baseObject = super.getBaseMetadata();
        const generativeQuestionAnsweringId = state.search?.response?.extendedResults?.generativeQuestionAnsweringId;
        if (generativeQuestionAnsweringId) {
            baseObject.generativeQuestionAnsweringId = generativeQuestionAnsweringId;
        }
        return baseObject;
    }
    getGeneratedAnswerMetadata() {
        const state = this.getState();
        return {
            ...(state.generatedAnswer?.isVisible !== undefined && {
                showGeneratedAnswer: state.generatedAnswer.isVisible,
            }),
        };
    }
    get queryText() {
        return this.state.query?.q || getQueryInitialState().q;
    }
    get responseTime() {
        return this.state.search?.duration || getSearchInitialState().duration;
    }
    mapResultsToAnalyticsDocument() {
        return this.state.search?.response.results.map((r) => ({
            documentUri: r.uri,
            documentUriHash: r.raw.urihash,
        }));
    }
    get numberOfResults() {
        return (this.state.search?.response.results.length ||
            getSearchInitialState().response.results.length);
    }
}
export const configureInsightAnalytics = ({ logger, getState, analyticsClientMiddleware = (_, p) => p, preprocessRequest, provider = new InsightAnalyticsProvider(getState), }) => {
    const state = getState();
    const token = state.configuration.accessToken;
    const apiBaseUrl = state.configuration.analytics.apiBaseUrl ??
        getOrganizationEndpoint(state.configuration.organizationId, state.configuration.environment, 'analytics');
    const runtimeEnvironment = state.configuration.analytics.runtimeEnvironment;
    const enabled = state.configuration.analytics.enabled;
    const client = new CoveoInsightClient({
        enableAnalytics: enabled,
        token,
        endpoint: apiBaseUrl,
        runtimeEnvironment,
        preprocessRequest: wrapPreprocessRequest(logger, preprocessRequest),
        beforeSendHooks: [
            wrapAnalyticsClientSendEventHook(logger, analyticsClientMiddleware),
            (type, payload) => {
                logger.info({
                    ...payload,
                    type,
                    endpoint: apiBaseUrl,
                    token,
                }, 'Analytics request');
                return payload;
            },
        ],
    }, provider);
    if (!enabled) {
        client.disable();
    }
    return client;
};
