import { tap, distinctUntilChanged, ignoreElements } from "rxjs/operators"
import { actions$, ofType } from "mini-rx-store"
import { $store } from "@racletteCore"

const interactionLinksEffects = (store) => {
  const dataUpdate = actions$.pipe(
    ofType("interactionLinks/set"),
    distinctUntilChanged((prev, curr) => !store.hasChanges(prev, curr)),

    tap((action) => {
      if (!action.actionResult?.added.length) return
      let landingCompositionId
      action.actionResult.added.forEach((link) => {
        if (link.isLandingPage) {
          landingCompositionId = link.composition
        }
      })
      if (!landingCompositionId) return
      const landingComposition = $store.getState([
        "compositions",
        landingCompositionId,
      ])
      const landingPagePath = landingComposition?.pathname?.default
      if (!landingPagePath) return
      $store.dispatch({
        type: "ui/update",
        payload: {
          landingPage: landingPagePath,
        },
      })
    }),
    ignoreElements(),
  )
  return [dataUpdate]
}

export default interactionLinksEffects
