import { tap, distinctUntilChanged, ignoreElements } from "rxjs/operators"
import { actions$, ofType } from "mini-rx-store"
import { getData } from "@racletteCore/lib/data/dataApi"
import log from "@racletteCore/lib/logger"
const queriesEffects = (store) => {
  const queriesAddExecute = actions$.pipe(
    ofType("queries/add/execute"),
    distinctUntilChanged((prev, curr) => !store.hasChanges(prev, curr)),

    tap((action) =>
      action.actionResult.added?.forEach((query) =>
        store.dispatch({
          type: "queries/execute",
          payload: {
            actionId: query.actionId,
            reset: true,
            target: query.target,
            params: query.params,
          },
        }),
      ),
    ),
    ignoreElements(),
  )
  const queriesExecute = actions$.pipe(
    ofType("queries/execute"),
    distinctUntilChanged((prev, curr) => !store.hasChanges(prev, curr)),

    tap((action) => {
      if (Object.keys(action.actionResult?.updated?.items).length) {
        Object.values(action.actionResult.updated.items).forEach((query) => {
          getData(query.actionId, query.target, query.params || false, {})
        })
      }
    }),
    ignoreElements(),
  )
  const queryiesSetCacheKey = actions$.pipe(
    ofType("queries/setCacheKey"),
    distinctUntilChanged((prev, curr) => !store.hasChanges(prev, curr)),

    tap((action) => {
      const updatedQuery = action?.actionResult?.updated || null
      if (updatedQuery) {
        const { item, itemBefore } = updatedQuery
        const { actionId } = action
        if (itemBefore?.cacheKey && itemBefore?.cacheKey !== item?.cacheKey) {
          store.dispatch({
            type: "queriesCache/remove",
            payload: { cacheKey: itemBefore.cacheKey, actionId },
          })
        }
      }
    }),
    ignoreElements(),
  )
  return [queriesAddExecute, queriesExecute, queryiesSetCacheKey]
}

export default queriesEffects
