import { useCallback } from 'react';

import { ICollectionComponentState } from '../state/ICollectionComponentState';
import { useSyncCollectionOnEntityReturn } from './useSyncCollectionOnEntityReturn';
import { CollectionState } from '@wix/bex-core';

export function useSyncCollectionOnEntityCreate<
  T,
  S extends ICollectionComponentState,
>(
  cachedState?: S,
  getCollectionsToUpdate?: (state: S, entity: T) => CollectionState<T>[] | null,
) {
  const updateCollection = useCallback(
    (collection: CollectionState<T>, entity: T) => {
      collection.addItem(entity);
    },
    [],
  );

  const checkIfViewSynced = useCallback(
    async (collection: CollectionState<T>, entity: T) => {
      const updatedData = await collection.fetchData({
        ...collection.query.asComputed,
        page: 1,
        cursor: null,
        offset: 0,
      });

      return (
        collection.itemKey(updatedData.items[0]) === collection.itemKey(entity)
      );
    },
    [cachedState],
  );

  useSyncCollectionOnEntityReturn({
    cachedState,
    updateCollection,
    checkIfViewSynced,
    getEntityFromRouterState: (state: { _createdEntity?: T }) =>
      state._createdEntity,
    getCollectionsToUpdate,
  });
}
