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

import { setAiPlaylistModeAction } from '../../../../TabPlaylist/redux/slices';
import { createAiPlaylistAction, updatePlaylistAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import {
  configAction,
  configChangedEventAction,
  isFilterDirtyAction,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';
import { playlistsEntitiesSelector } from '@/modules/editorial/RightSideBar/TabWatch/Watches/redux/selectors';

import { getDefaultConfig, getEmptySearchOrderConfig } from '@/modules/editorial/editorialSearchFilter/filterConfig';

const queryGQL = `
  mutation createAiPlaylist(
    $watchId: Int!,
    $channelId: Int!,
    $type: String!,
    $length: Int,
  ) {
    createAiPlaylist(
      watchId: $watchId,
      channelId: $channelId,
      type: $type,
      length: $length,
    ) {
      id
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createAiPlaylistAction.type),
    concatMap(({ payload: { watchId, channelId, playlistId, publisherId, type } }) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          watchId,
          channelId,
          type,
        },
      }).pipe(
        concatMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const config = getDefaultConfig();

            const defaultOrderConfig = getEmptySearchOrderConfig();

            const filterConfig = {
              ...config,
              ...defaultOrderConfig,
            };

            const playlists = playlistsEntitiesSelector(state$.value);
            const playlist = playlists[playlistId];

            actions.push(
              of(configAction(filterConfig)),
              of(configChangedEventAction()),
              of(isFilterDirtyAction(false)),
              of(
                updatePlaylistAction({
                  clips: [...(playlist.clips ?? []), `${data.createAiPlaylist.id}`],
                  playlistId,
                  publisherId,
                  callBackAction: () => setAiPlaylistModeAction(true),
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(stream$);
    }),
  );
