import { buildBrowserEnvironment, createRelay, } from '@coveo/relay';
import { createSelector } from '@reduxjs/toolkit';
import { isBrowser } from '../../utils/runtime.js';
import { getAnalyticsNextApiBaseUrl } from '../platform-client.js';
import { getAnalyticsSource } from './analytics-selectors.js';
export const getRelayInstanceFromState = createSelector((state) => state.configuration.organizationId, (state) => state.configuration.environment, (state) => state.configuration.accessToken, (state) => state.configuration.analytics, (state) => getAnalyticsSource(state.configuration.analytics), (_state, navigatorContextProvider) => navigatorContextProvider, (organizationId, platformEnvironment, token, { trackingId, apiBaseUrl, enabled }, source, navigatorContextProvider) => {
    const environment = getEnvironment(navigatorContextProvider);
    return createRelay({
        mode: enabled ? 'emit' : 'disabled',
        url: apiBaseUrl ??
            getAnalyticsNextApiBaseUrl(organizationId, platformEnvironment),
        token,
        trackingId: trackingId ?? null,
        source,
        environment,
    });
});
const noopRelayEnvironment = {
    getClientId: () => '',
    getLocation: () => null,
    getReferrer: () => null,
    getUserAgent: () => null,
    send: async () => { },
};
const getEnvironment = (customProvider) => {
    if (!customProvider) {
        return undefined;
    }
    const customContext = customProvider();
    const baseEnvironment = isBrowser()
        ? buildBrowserEnvironment()
        : noopRelayEnvironment;
    return {
        ...baseEnvironment,
        getClientId: () => customContext.clientId,
        getLocation: () => customContext.location,
        getReferrer: () => customContext.referrer,
        getUserAgent: () => customContext.userAgent,
    };
};
