import { createReducer } from '@reduxjs/toolkit';
import { setError } from '../../error/error-actions.js';
import { setContext, setView } from '../context/context-actions.js';
import { fetchMoreProducts, fetchProductListing, promoteChildToParent, } from './product-listing-actions.js';
import { getProductListingInitialState, } from './product-listing-state.js';
export const productListingReducer = createReducer(getProductListingInitialState(), (builder) => {
    builder
        .addCase(fetchProductListing.rejected, (state, action) => {
        handleError(state, action.payload);
    })
        .addCase(fetchMoreProducts.rejected, (state, action) => {
        handleError(state, action.payload);
    })
        .addCase(fetchProductListing.fulfilled, (state, action) => {
        const paginationOffset = getPaginationOffset(action.payload);
        handleFullfilled(state, action.payload.response);
        state.products = action.payload.response.products.map((product, index) => preprocessProduct(product, paginationOffset + index + 1, action.payload.response.responseId));
    })
        .addCase(fetchMoreProducts.fulfilled, (state, action) => {
        if (!action.payload) {
            return;
        }
        const paginationOffset = getPaginationOffset(action.payload);
        handleFullfilled(state, action.payload.response);
        state.products = state.products.concat(action.payload.response.products.map((product, index) => preprocessProduct(product, paginationOffset + index + 1, action.payload?.response.responseId)));
    })
        .addCase(fetchProductListing.pending, (state, action) => {
        handlePending(state, action.meta.requestId);
    })
        .addCase(fetchMoreProducts.pending, (state, action) => {
        handlePending(state, action.meta.requestId);
    })
        .addCase(promoteChildToParent, (state, action) => {
        const { products } = state;
        let childToPromote;
        const currentParentIndex = products.findIndex((product) => {
            childToPromote = product.children.find((child) => child.permanentid === action.payload.child.permanentid);
            return !!childToPromote;
        });
        if (currentParentIndex === -1 || childToPromote === undefined) {
            return;
        }
        const responseId = products[currentParentIndex].responseId;
        const position = products[currentParentIndex].position;
        const { children, totalNumberOfChildren } = products[currentParentIndex];
        const newParent = {
            ...childToPromote,
            children,
            totalNumberOfChildren,
            position,
            responseId,
        };
        products.splice(currentParentIndex, 1, newParent);
    })
        .addCase(setView, () => getProductListingInitialState())
        .addCase(setContext, () => getProductListingInitialState())
        .addCase(setError, (state, action) => {
        handleError(state, action.payload);
    });
});
function handleError(state, error) {
    state.error = error || null;
    state.isLoading = false;
}
function handleFullfilled(state, response) {
    state.error = null;
    state.facets = response.facets;
    state.responseId = response.responseId;
    state.isLoading = false;
}
function handlePending(state, requestId) {
    state.isLoading = true;
    state.requestId = requestId;
}
function getPaginationOffset(payload) {
    const pagination = payload.response.pagination;
    return pagination.page * pagination.perPage;
}
function preprocessProduct(product, position, responseId) {
    const isParentAlreadyInChildren = product.children.some((child) => child.permanentid === product.permanentid);
    if (product.children.length === 0 || isParentAlreadyInChildren) {
        return { ...product, position, responseId };
    }
    const { children, totalNumberOfChildren: _totalNumberOfChildren, ...restOfProduct } = product;
    return {
        ...product,
        children: [restOfProduct, ...children],
        position,
        responseId,
    };
}
