import type { InteractionLinksState } from "@racletteCore/store/types/index"
import useStateSubscriber from "@racletteOrchestrator/composables/useStateSubscriber"
import { computed } from "vue"
import { clone } from "ramda"
import type { InteractionLink } from "@shared/types"

type UseInteractionLinksSettings = {
  filterTriggers?: boolean
}

type InteractionLinkTriggerType = InteractionLink["triggers"][number]["type"]

export default (
  triggerType?: InteractionLinkTriggerType | InteractionLinkTriggerType[],
  settings: UseInteractionLinksSettings = {
    filterTriggers: true,
  },
) => {
  // normalize triggerType to an array (only if defined)
  const _triggerType =
    triggerType === undefined
      ? undefined
      : typeof triggerType === "string"
        ? [triggerType]
        : clone(triggerType)

  const { state } =
    useStateSubscriber<InteractionLinksState>("interactionLinks")

  const filteredInteractionLinks = computed(() => {
    if (!_triggerType) {
      return Object.values(state.value)
    }

    let filteredState = Object.values(state.value).filter((interactionLink) =>
      interactionLink.triggers.some((trigger) =>
        _triggerType.includes(trigger.type),
      ),
    )

    if (settings.filterTriggers) {
      filteredState = clone(filteredState)

      filteredState.forEach((interactionLink) => {
        interactionLink.triggers = interactionLink.triggers.filter((trigger) =>
          _triggerType.includes(trigger.type),
        )
      })
    }

    return filteredState
  })

  return { state: filteredInteractionLinks }
}
