import { CoveoSearchPageClient, } 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 { getSortCriteriaInitialState } from '../../features/sort-criteria/sort-criteria-state.js';
import { getOrganizationEndpoint } from '../platform-client.js';
import { BaseAnalyticsProvider } from './base-analytics.js';
import HistoryStore from './coveo.analytics/history-store.js';
import { wrapAnalyticsClientSendEventHook, wrapPreprocessRequest, } from './coveo-analytics-utils.js';
export class SearchAnalyticsProvider extends BaseAnalyticsProvider {
    static fallbackPipelineName = 'default';
    getFacetState() {
        return buildFacetStateMetadata(getStateNeededForFacetMetadata(this.getState()));
    }
    getPipeline() {
        return (this.state.pipeline ||
            this.state.search?.response.pipeline ||
            SearchAnalyticsProvider.fallbackPipelineName);
    }
    getSearchEventRequestPayload() {
        return {
            queryText: this.queryText,
            responseTime: this.responseTime,
            results: this.resultURIs,
            numberOfResults: this.numberOfResults,
        };
    }
    getSearchUID() {
        const newState = this.getState();
        return (newState.search?.searchResponseId ||
            newState.search?.response.searchUid ||
            getSearchInitialState().response.searchUid);
    }
    getSplitTestRunName() {
        return this.state.search?.response.splitTestRun;
    }
    getSplitTestRunVersion() {
        const hasSplitTestRun = !!this.getSplitTestRunName();
        const effectivePipelineWithSplitTestRun = this.state.search?.response.pipeline ||
            this.state.pipeline ||
            SearchAnalyticsProvider.fallbackPipelineName;
        return hasSplitTestRun ? effectivePipelineWithSplitTestRun : undefined;
    }
    getBaseMetadata() {
        const state = this.getState();
        const baseObject = super.getBaseMetadata();
        const generativeQuestionAnsweringId = state.search?.response?.extendedResults?.generativeQuestionAnsweringId;
        if (generativeQuestionAnsweringId) {
            baseObject.generativeQuestionAnsweringId = generativeQuestionAnsweringId;
        }
        return baseObject;
    }
    getFacetMetadata(facetId, facetValue) {
        const facetRequest = this.getFacetRequest(facetId);
        const facetField = facetRequest?.field ?? '';
        return {
            ...this.getBaseMetadata(),
            facetId,
            facetField,
            facetValue,
            facetTitle: `${facetField}_${facetId}`,
        };
    }
    getFacetClearAllMetadata(facetId) {
        const facetRequest = this.getFacetRequest(facetId);
        const facetField = facetRequest?.field ?? '';
        return {
            ...this.getBaseMetadata(),
            facetId,
            facetField,
            facetTitle: `${facetField}_${facetId}`,
        };
    }
    getFacetUpdateSortMetadata(facetId, criteria) {
        const facetRequest = this.getFacetRequest(facetId);
        const facetField = facetRequest?.field ?? '';
        return {
            ...this.getBaseMetadata(),
            facetId,
            facetField,
            criteria,
            facetTitle: `${facetField}_${facetId}`,
        };
    }
    getRangeBreadcrumbFacetMetadata(facetId, facetValue) {
        const facetRequest = this.getFacetRequest(facetId);
        const facetField = facetRequest?.field ?? '';
        return {
            ...this.getBaseMetadata(),
            facetId,
            facetField,
            facetRangeEnd: facetValue.end,
            facetRangeEndInclusive: facetValue.endInclusive,
            facetRangeStart: facetValue.start,
            facetTitle: `${facetField}_${facetId}`,
        };
    }
    getFacetRequest = (id) => {
        return (this.state.facetSet?.[id]?.request ||
            this.state.categoryFacetSet?.[id]?.request ||
            this.state.dateFacetSet?.[id]?.request ||
            this.state.numericFacetSet?.[id]?.request ||
            this.state.automaticFacetSet?.set[id]?.response);
    };
    getResultSortMetadata() {
        return {
            ...this.getBaseMetadata(),
            resultsSortBy: this.state.sortCriteria ?? getSortCriteriaInitialState(),
        };
    }
    getStaticFilterToggleMetadata(staticFilterId, staticFilterValue) {
        return {
            ...this.getBaseMetadata(),
            staticFilterId,
            staticFilterValue,
        };
    }
    getStaticFilterClearAllMetadata(staticFilterId) {
        return {
            ...this.getBaseMetadata(),
            staticFilterId,
        };
    }
    getUndoTriggerQueryMetadata(undoneQuery) {
        return {
            ...this.getBaseMetadata(),
            undoneQuery,
        };
    }
    getCategoryBreadcrumbFacetMetadata(categoryFacetId, categoryFacetPath) {
        const facetRequest = this.getFacetRequest(categoryFacetId);
        const categoryFacetField = facetRequest?.field ?? '';
        return {
            ...this.getBaseMetadata(),
            categoryFacetId,
            categoryFacetField,
            categoryFacetPath,
            categoryFacetTitle: `${categoryFacetField}_${categoryFacetId}`,
        };
    }
    getOmniboxAnalyticsMetadata(id, suggestion) {
        const querySuggest = this.state.querySuggest?.[id];
        const suggestions = querySuggest.completions.map((completion) => completion.expression);
        const lastIndex = querySuggest.partialQueries.length - 1;
        const partialQuery = querySuggest.partialQueries[lastIndex] || '';
        const querySuggestResponseId = querySuggest.responseId;
        return {
            ...this.getBaseMetadata(),
            suggestionRanking: suggestions.indexOf(suggestion),
            partialQuery,
            partialQueries: querySuggest.partialQueries.length > 0
                ? querySuggest.partialQueries
                : '',
            suggestions: suggestions.length > 0 ? suggestions : '',
            querySuggestResponseId,
        };
    }
    getInterfaceChangeMetadata() {
        return {
            ...this.getBaseMetadata(),
            interfaceChangeTo: this.state.configuration.analytics.originLevel2,
        };
    }
    getOmniboxFromLinkMetadata(metadata) {
        return {
            ...this.getBaseMetadata(),
            ...metadata,
        };
    }
    getGeneratedAnswerMetadata() {
        const state = this.getState();
        const formattedObject = {};
        if (state.generatedAnswer?.isVisible !== undefined) {
            formattedObject.showGeneratedAnswer = state.generatedAnswer.isVisible;
        }
        return formattedObject;
    }
    get resultURIs() {
        return this.results?.map((r) => ({
            documentUri: r.uri,
            documentUriHash: r.raw.urihash,
        }));
    }
    get results() {
        return this.state.search?.response.results;
    }
    get queryText() {
        return this.state.query?.q || getQueryInitialState().q;
    }
    get responseTime() {
        return this.state.search?.duration || getSearchInitialState().duration;
    }
    get numberOfResults() {
        return (this.state.search?.response.totalCountFiltered ||
            getSearchInitialState().response.totalCountFiltered);
    }
}
//TODO: KIT-2859
export const configureLegacyAnalytics = ({ logger, getState, analyticsClientMiddleware = (_, p) => p, preprocessRequest, provider = new SearchAnalyticsProvider(getState), }) => {
    const state = getState();
    const token = state.configuration.accessToken;
    const endpoint = state.configuration.analytics.apiBaseUrl ??
        getOrganizationEndpoint(state.configuration.organizationId, state.configuration.environment, 'analytics');
    const runtimeEnvironment = state.configuration.analytics.runtimeEnvironment;
    const enableAnalytics = state.configuration.analytics.enabled;
    const client = new CoveoSearchPageClient({
        token,
        endpoint,
        runtimeEnvironment,
        preprocessRequest: wrapPreprocessRequest(logger, preprocessRequest),
        beforeSendHooks: [
            wrapAnalyticsClientSendEventHook(logger, analyticsClientMiddleware),
            (type, payload) => {
                logger.info({
                    ...payload,
                    type,
                    endpoint,
                    token,
                }, 'Analytics request');
                return payload;
            },
        ],
    }, provider);
    if (!enableAnalytics) {
        client.disable();
    }
    return client;
};
export const getPageID = () => {
    const actions = HistoryStore.getInstance().getHistory();
    const lastPageView = actions.reverse().find((action) => {
        return action.name === 'PageView' && action.value;
    });
    if (!lastPageView) {
        return '';
    }
    return lastPageView.value;
};
