import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import { getVisitorID } from '../../api/analytics/coveo-analytics-utils.js';
import { getOrganizationEndpoint } from '../../api/platform-client.js';
import { isErrorResponse } from '../../api/search/search-api-client.js';
import { prepareContextFromFields } from '../../api/service/case-assist/case-assist-params.js';
import { requiredEmptyAllowedString, requiredNonEmptyString, validatePayload, } from '../../utils/validate-payload.js';
export const registerCaseField = createAction('caseAssist/caseField/register', (payload) => validatePayload(payload, {
    fieldName: requiredNonEmptyString,
    fieldValue: requiredEmptyAllowedString,
}));
export const updateCaseField = createAction('caseAssist/caseField/update', (payload) => validatePayload(payload, {
    fieldName: requiredNonEmptyString,
    fieldValue: requiredEmptyAllowedString,
}));
export const fetchCaseClassifications = createAsyncThunk('caseAssist/classifications/fetch', async (_, { getState, rejectWithValue, extra: { apiClient } }) => {
    const state = getState();
    const fetched = await apiClient.getCaseClassifications(await buildFetchClassificationRequest(state));
    if (isErrorResponse(fetched)) {
        return rejectWithValue(fetched.error);
    }
    return {
        response: fetched.success,
    };
});
export const buildFetchClassificationRequest = async (state) => ({
    accessToken: state.configuration.accessToken,
    organizationId: state.configuration.organizationId,
    url: state.caseAssistConfiguration.apiBaseUrl ??
        getOrganizationEndpoint(state.configuration.organizationId, state.configuration.environment),
    caseAssistId: state.caseAssistConfiguration.caseAssistId,
    ...(state.configuration.analytics.enabled && {
        clientId: await getVisitorID(state.configuration.analytics),
    }),
    fields: state.caseInput,
    context: state.caseField
        ? prepareContextFromFields(state.caseField.fields)
        : undefined,
    locale: state.caseAssistConfiguration.locale,
    debug: state.debug,
});
