import React from "react";
import { RootState, useAppDispatch, useAppSelector } from "store";
import { SubscriptionsStore } from "subscriptions/domain/subscriptionsStore";
import { SubscriptionRequest } from "./dto/subscriptionRequest";
import {
  getSessionAction,
  getSubscriptionsAction,
  subscribeAction,
} from "./subscriptionsActions";
import { SubscriptionsStoreState } from "./subscriptionsReducer";

const subscriptionsSelector = (state: RootState): SubscriptionsStoreState =>
  state.subscriptions;

const useSubscriptionsStore = (): SubscriptionsStore => {
  const { isFailed, isLoading, subscribing, subscriptions } = useAppSelector(
    subscriptionsSelector
  );

  const dispatch = useAppDispatch();

  const get = React.useCallback(
    () => getSubscriptionsAction()(dispatch),
    [dispatch]
  );

  const subscribe = React.useCallback(
    (payload: SubscriptionRequest) => subscribeAction(payload)(dispatch),
    [dispatch]
  );

  const forkTo = React.useCallback(
    (id: string) => getSessionAction(id)(dispatch),
    [dispatch]
  );

  return {
    isFailed,
    isLoading,
    subscribing,
    subscriptions,
    forkTo,
    subscribe,
    get,
  };
};

export { useSubscriptionsStore };
