import { NumberValue } from '@coveo/bueno';
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import HistoryStore from '../../api/analytics/coveo.analytics/history-store.js';
import { getSearchApiBaseUrl } from '../../api/platform-client.js';
import { isErrorResponse, } from '../../api/search/search-api-client.js';
import { requiredEmptyAllowedString, requiredNonEmptyString, validatePayload, } from '../../utils/validate-payload.js';
import { fromAnalyticsStateToAnalyticsParams } from '../configuration/analytics-params.js';
import { fromAnalyticsStateToAnalyticsParams as legacyFromAnalyticsStateToAnalyticsParams } from '../configuration/legacy-analytics-params.js';
export const idDefinition = {
    id: requiredNonEmptyString,
};
export const registerQuerySuggest = createAction('querySuggest/register', (payload) => validatePayload(payload, {
    ...idDefinition,
    count: new NumberValue({ min: 0 }),
}));
export const unregisterQuerySuggest = createAction('querySuggest/unregister', (payload) => validatePayload(payload, idDefinition));
export const selectQuerySuggestion = createAction('querySuggest/selectSuggestion', (payload) => validatePayload(payload, {
    ...idDefinition,
    expression: requiredEmptyAllowedString,
}));
export const clearQuerySuggest = createAction('querySuggest/clear', (payload) => validatePayload(payload, idDefinition));
export const fetchQuerySuggestions = createAsyncThunk('querySuggest/fetch', async (payload, { getState, rejectWithValue, extra: { apiClient, validatePayload, navigatorContext }, }) => {
    validatePayload(payload, idDefinition);
    const id = payload.id;
    const request = await buildQuerySuggestRequest(id, getState(), navigatorContext);
    const response = await apiClient.querySuggest(request);
    if (isErrorResponse(response)) {
        return rejectWithValue(response.error);
    }
    return {
        id,
        q: request.q,
        ...response.success,
    };
});
export const buildQuerySuggestRequest = async (id, s, navigatorContext) => {
    return {
        accessToken: s.configuration.accessToken,
        organizationId: s.configuration.organizationId,
        url: s.configuration.search.apiBaseUrl ??
            getSearchApiBaseUrl(s.configuration.organizationId, s.configuration.environment),
        count: s.querySuggest[id].count,
        q: s.querySet[id],
        locale: s.configuration.search.locale,
        timezone: s.configuration.search.timezone,
        actionsHistory: s.configuration.analytics.enabled
            ? HistoryStore.getInstance().getHistory()
            : [],
        ...(s.context && { context: s.context.contextValues }),
        ...(s.pipeline && { pipeline: s.pipeline }),
        ...(s.searchHub && { searchHub: s.searchHub }),
        tab: s.configuration.analytics.originLevel2,
        ...(s.configuration.analytics.enabled && {
            ...(s.configuration.analytics.enabled &&
                s.configuration.analytics.analyticsMode === 'legacy'
                ? await legacyFromAnalyticsStateToAnalyticsParams(s.configuration.analytics)
                : fromAnalyticsStateToAnalyticsParams(s.configuration.analytics, navigatorContext)),
        }),
        ...(s.configuration.search.authenticationProviders.length && {
            authentication: s.configuration.search.authenticationProviders.join(','),
        }),
    };
};
