import {
  CollectionOptimisticActions,
  CollectionOptimisticActionsBaseParams,
  CollectionOptimisticSequenceExecutor,
  CollectionState,
  Filter,
  FiltersMap,
  QueryState,
  WixPatternsContainer,
} from '@wix/bex-core';
import { NestedTableLevelDescriptor } from './NestedTableLevelDescriptor';
import { createParentIdPredicate } from './createParentIdPredicate';

export interface NestedOptimisticActionsState<T, F extends FiltersMap> {
  readonly parentId?: string;
  readonly sequences?: Map<string, CollectionOptimisticSequenceExecutor>;
  readonly query?: QueryState<F>;
  readonly levelDescriptor: NestedTableLevelDescriptor<string, T, F>;
  parentFilter?: Filter<string[]>;
}

export function createNestedOptimisticActions<T, F extends FiltersMap>(
  container: WixPatternsContainer,
  collection: CollectionState<T, F>,
  state?: NestedOptimisticActionsState<T, F>,
  params?: Partial<CollectionOptimisticActionsBaseParams<T, F>>,
) {
  const parentIdPredicate = createParentIdPredicate(state);

  const optimisticActions =
    collection._optimisticActions ??
    new CollectionOptimisticActions({
      container,
      collection,
      orderBy: () => [],
      ...params,
      predicate: (query) => {
        const originalPredicateForQuery =
          params?.predicate?.(query) ??
          state?.levelDescriptor?.optimisticActionsPredicate?.(query);

        const parentIdPredicateForQuery = parentIdPredicate(query);

        return (item) =>
          parentIdPredicateForQuery(item) &&
          (originalPredicateForQuery?.(item) ?? true);
      },
      cacheNamespace: state?.parentId,
      sequences: state?.sequences,
      query: state?.query,
    });

  optimisticActions._commitMode = false;

  return optimisticActions;
}
