import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { TRENDING } from '@/modules/editorial/constants/video';

import filtersToParams from '../../helpers/filter';
import filtersToInternalParams from '../../helpers/filterInternal';
import {
  filterInternalParamsAction,
  filterParamsAction,
  restartSearchEventAction,
  searchFiltersAction,
  startSearchEventAction,
} from '../slices';
import { deepClone } from '@/modules/@common/helpers';
import {
  getPublisherIdsSelector,
  getUserContentOwnersSelector,
  getUserPermissionsSelector,
} from '@/modules/@common/user/redux/selectors';
import { playlistTypeSelector } from '@/modules/editorial/editorialSearch/reduxSearch/selectors';
import { searchEventAction } from '@/modules/editorial/editorialSearch/reduxSearch/slices';
import {
  configSelector,
  isInsightsModeSelector,
  isMoreFiltersOpenedSelector,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/selectors';
import { aiPlaylistModeSelector } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/selectors';

export default (action$, state$) =>
  action$.pipe(
    ofType(searchEventAction.type, restartSearchEventAction.type),
    switchMap(() => {
      const state = state$.value;
      const userPermissions = getUserPermissionsSelector(state);
      const configRaw = configSelector(state);
      const isInsightsMode = isInsightsModeSelector(state);
      const isMoreFiltersOpened = isMoreFiltersOpenedSelector(state);

      const userPublisherIds = getPublisherIdsSelector(state$.value);
      const userContentOwners = getUserContentOwnersSelector(state$.value);

      const playlistType = playlistTypeSelector(state);
      const aiPlaylistMode = aiPlaylistModeSelector(state$.value);

      const config = deepClone(configRaw);

      if (playlistType === TRENDING && aiPlaylistMode && isMoreFiltersOpened) {
        config.order.filters[0] = {
          label: 'Trending',
          value: 'trending',
          isSortable: false,
        };
      }

      const filterParams = filtersToParams(
        config,
        isInsightsMode,
        userPublisherIds,
        userContentOwners,
        userPermissions,
      );
      const filterInternalParams = filtersToInternalParams(
        config,
        isInsightsMode,
        userPublisherIds,
        userContentOwners,
        userPermissions,
      );

      return concat(
        of(searchFiltersAction(config)),
        of(filterParamsAction(filterParams)),
        of(filterInternalParamsAction(filterInternalParams)),
        of(startSearchEventAction()),
      );
    }),
  );
