import { BooleanValue, StringValue } from '@coveo/bueno';
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import { getSearchApiBaseUrl } from '../../api/platform-client.js';
import { ExecutionPlan } from '../../api/search/plan/plan-endpoint.js';
import { isErrorResponse, } from '../../api/search/search-api-client.js';
import { requiredNonEmptyString, validatePayload, } from '../../utils/validate-payload.js';
import { makeAnalyticsAction, } from '../analytics/analytics-utils.js';
import { fromAnalyticsStateToAnalyticsParams } from '../configuration/analytics-params.js';
import { fromAnalyticsStateToAnalyticsParams as legacyFromAnalyticsStateToAnalyticsParams } from '../configuration/legacy-analytics-params.js';
export const registerStandaloneSearchBox = createAction('standaloneSearchBox/register', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
    redirectionUrl: requiredNonEmptyString,
    overwrite: new BooleanValue({ required: false }),
}));
export const updateStandaloneSearchBoxRedirectionUrl = createAction('standaloneSearchBox/updateRedirectionUrl', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
    redirectionUrl: requiredNonEmptyString,
}));
export const resetStandaloneSearchBox = createAction('standaloneSearchBox/reset', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
}));
export const updateAnalyticsToSearchFromLink = createAction('standaloneSearchBox/updateAnalyticsToSearchFromLink', (payload) => validatePayload(payload, { id: requiredNonEmptyString }));
export const updateAnalyticsToOmniboxFromLink = createAction('standaloneSearchBox/updateAnalyticsToOmniboxFromLink');
export const fetchRedirectUrl = createAsyncThunk('standaloneSearchBox/fetchRedirect', async (payload, { dispatch, getState, rejectWithValue, extra: { apiClient, validatePayload, navigatorContext }, }) => {
    validatePayload(payload, { id: new StringValue({ emptyAllowed: false }) });
    const request = await buildPlanRequest(getState(), navigatorContext);
    const response = await apiClient.plan(request);
    if (isErrorResponse(response)) {
        return rejectWithValue(response.error);
    }
    const { redirectionUrl } = new ExecutionPlan(response.success);
    if (redirectionUrl) {
        dispatch(logRedirect(redirectionUrl));
    }
    return redirectionUrl || '';
});
const logRedirect = (url) => makeAnalyticsAction('analytics/standaloneSearchBox/redirect', (client) => client.makeTriggerRedirect({ redirectedTo: url }));
export const buildPlanRequest = async (state, navigatorContext) => {
    return {
        accessToken: state.configuration.accessToken,
        organizationId: state.configuration.organizationId,
        url: state.configuration.search.apiBaseUrl ??
            getSearchApiBaseUrl(state.configuration.organizationId, state.configuration.environment),
        locale: state.configuration.search.locale,
        timezone: state.configuration.search.timezone,
        q: state.query.q,
        ...(state.context && { context: state.context.contextValues }),
        ...(state.pipeline && { pipeline: state.pipeline }),
        ...(state.searchHub && { searchHub: state.searchHub }),
        ...(state.query.enableQuerySyntax && {
            enableQuerySyntax: state.query.enableQuerySyntax,
        }),
        ...(state.configuration.analytics.enabled &&
            state.configuration.analytics.analyticsMode === 'legacy'
            ? await legacyFromAnalyticsStateToAnalyticsParams(state.configuration.analytics)
            : fromAnalyticsStateToAnalyticsParams(state.configuration.analytics, navigatorContext)),
        ...(state.configuration.search.authenticationProviders.length && {
            authentication: state.configuration.search.authenticationProviders.join(','),
        }),
    };
};
