import { BooleanValue, StringValue } from '@coveo/bueno';
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import { isErrorResponse, } from '../../../api/commerce/commerce-api-client.js';
import { isRedirectTrigger } from '../../../api/common/trigger.js';
import { requiredNonEmptyString, validatePayload, } from '../../../utils/validate-payload.js';
import { buildPlanRequest, } from './plan-request-builder.js';
// eslint-disable-next-line @cspell/spellchecker
// TODO: CAPI-867 - Use Commerce API's equivalent of the /plan endpoint when it becomes available.
export const fetchRedirectUrl = createAsyncThunk('commerce/standaloneSearchBox/fetchRedirect', async (payload, { getState, rejectWithValue, extra: { apiClient, navigatorContext } }) => {
    validatePayload(payload, { id: new StringValue({ emptyAllowed: false }) });
    const state = getState();
    const request = buildPlanRequest(state, navigatorContext);
    const response = await apiClient.plan(request);
    if (isErrorResponse(response)) {
        return rejectWithValue(response.error);
    }
    const redirectTriggers = response.success.triggers.filter(isRedirectTrigger);
    return redirectTriggers.length ? redirectTriggers[0].content : '';
});
export const registerStandaloneSearchBox = createAction('commerce/standaloneSearchBox/register', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
    redirectionUrl: requiredNonEmptyString,
    overwrite: new BooleanValue({ required: false }),
}));
export const updateStandaloneSearchBoxRedirectionUrl = createAction('commerce/standaloneSearchBox/updateRedirectionUrl', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
    redirectionUrl: requiredNonEmptyString,
}));
export const resetStandaloneSearchBox = createAction('commerce/standaloneSearchBox/reset', (payload) => validatePayload(payload, {
    id: requiredNonEmptyString,
}));
