import { RecordValue, StringValue } from '@coveo/bueno';
import { createAction, createAsyncThunk } from '@reduxjs/toolkit';
import { isErrorResponse, } from '../../../api/commerce/commerce-api-client.js';
import { validatePayload } from '../../../utils/validate-payload.js';
import { buildFilterableCommerceAPIRequest, } from '../common/filterable-commerce-api-request-builder.js';
import { perPagePrincipalSelector } from '../pagination/pagination-selectors.js';
import { moreProductsAvailableSelector, numberOfProductsSelector, } from './product-listing-selectors.js';
export const fetchProductListing = createAsyncThunk('commerce/productListing/fetch', async (_action, { getState, rejectWithValue, extra: { apiClient, navigatorContext } }) => {
    const state = getState();
    const fetched = await apiClient.getProductListing(buildFilterableCommerceAPIRequest(state, navigatorContext));
    if (isErrorResponse(fetched)) {
        return rejectWithValue(fetched.error);
    }
    return {
        response: fetched.success,
    };
});
export const fetchMoreProducts = createAsyncThunk('commerce/productListing/fetchMoreProducts', async (_action, { getState, rejectWithValue, extra: { apiClient, navigatorContext } }) => {
    const state = getState();
    const moreProductsAvailable = moreProductsAvailableSelector(state);
    if (!moreProductsAvailable) {
        return null;
    }
    const perPage = perPagePrincipalSelector(state);
    const numberOfProducts = numberOfProductsSelector(state);
    const nextPageToRequest = numberOfProducts / perPage;
    const fetched = await apiClient.getProductListing({
        ...buildFilterableCommerceAPIRequest(state, navigatorContext),
        page: nextPageToRequest,
    });
    if (isErrorResponse(fetched)) {
        return rejectWithValue(fetched.error);
    }
    return {
        response: fetched.success,
    };
});
const promoteChildToParentDefinition = {
    child: new RecordValue({
        options: { required: true },
        values: {
            permanentid: new StringValue({ required: true }),
        },
    }),
};
export const promoteChildToParent = createAction('commerce/productListing/promoteChildToParent', (payload) => validatePayload(payload, promoteChildToParentDefinition));
