import { ComputedQuery, FiltersMap } from '@wix/bex-core';
import { NestedOptimisticActionsState } from './createNestedOptimisticActions';

export function createParentIdPredicate<T, F extends FiltersMap>(
  state?: NestedOptimisticActionsState<T, F>,
) {
  const parentFilterName = state?.parentFilter?.name;

  return (query: ComputedQuery<F>) => {
    const parentId = parentFilterName
      ? (query.filters?.[parentFilterName] as string[] | undefined)
      : undefined;

    return (item: T) => {
      const itemParentId = state?.levelDescriptor?.parentKey(item);

      if (
        parentId &&
        parentId.length &&
        !parentId.some((p) =>
          p === 'null' ? itemParentId == null : itemParentId === p,
        )
      ) {
        return false;
      }

      return true;
    };
  };
}
