import { AnyAction } from "@reduxjs/toolkit";
import { SubscriptionsStore } from "subscriptions/domain/subscriptionsStore";
import * as actionTypes from "./subscriptionsActionTypes";

type SubscriptionsStoreState = Omit<
  SubscriptionsStore,
  "get" | "forkTo" | "subscribe"
>;

const INITIAL_STATE: SubscriptionsStoreState = {
  isLoading: true,
  isFailed: false,
  subscribing: [],
  subscriptions: undefined,
};

const subscriptionsReducer = (
  state: SubscriptionsStoreState = INITIAL_STATE,
  action: AnyAction
): SubscriptionsStoreState => {
  switch (action.type) {
    /* ------------------------- Subscriptions fetching ------------------------- */
    case actionTypes.SUBSCRIPTIONS_LOAD:
      return {
        ...state,
        isLoading: typeof state.subscriptions === typeof undefined,
      };
    case actionTypes.SUBSCRIPTIONS_LOAD_SUCCESS:
      return {
        ...state,
        isLoading: false,
        subscriptions: action.payload,
      };
    case actionTypes.SUBSCRIPTIONS_LOAD_FAILURE:
      return {
        ...state,
        isFailed: true,
        isLoading: false,
      };
    /* --------------------------- Services management -------------------------- */
    case actionTypes.SUBSCRIBE_SERVICE:
      return {
        ...state,
        subscribing: [...(state.subscribing ?? []), action.payload],
      };
    case actionTypes.SUBSCRIBE_SERVICE_SUCCESS:
      return {
        ...state,
        subscriptions: [...(state.subscriptions ?? []), action.payload],
        subscribing: state.subscribing?.filter(
          (item) => item !== action.payload
        ),
      };
    case actionTypes.SUBSCRIBE_SERVICE_FAILED:
      return {
        ...state,
        subscribing: state.subscribing?.filter(
          (item) => item !== action.payload
        ),
      };
    /* --------------------------------- Default -------------------------------- */
    default:
      return state;
  }
};

export { subscriptionsReducer };
export type { SubscriptionsStoreState };
