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

import { createAiPlaylistAction, setAiPlaylistModeAction, updatePlaylistAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';
import { playlistTypeAction } from '@/modules/editorial/editorialSearch/reduxSearch/slices';
import {
  configAction,
  configChangedEventAction,
  isFilterDirtyAction,
} from '@/modules/editorial/editorialSearchFilter/filterContainer/redux/slices';
import { aiPlaylistIdAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { playlistsSelector } from '@/modules/editorial/RightSideBar/TabPlaylist/redux/selectors';

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

const queryGQL = `
  mutation createEditorialAiPlaylist(
    $editorialPlaylistId: Int!,
    $type: String!,
    $length: Int,
  ) {
    createEditorialAiPlaylist(
      editorialPlaylistId: $editorialPlaylistId,
      type: $type,
      length: $length,
    ) {
      id
    }
  }
`;

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

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

            const defaultOrderConfig = getEmptySearchOrderConfig();

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

            const playlists = playlistsSelector(state$.value);
            const playlist = playlists.find((playlist$) => playlist$.id === playlistId);

            actions.push(
              of(configAction(filterConfig)),
              of(configChangedEventAction()),
              of(isFilterDirtyAction(false)),
              of(
                updatePlaylistAction({
                  clips: [...(playlist.clips ?? []), `${data.createEditorialAiPlaylist.id}`],
                  playlistId,
                  publisherId,
                }),
              ),
              of(aiPlaylistIdAction(data.createEditorialAiPlaylist.id)),
              of(playlistTypeAction(type)),
              of(setAiPlaylistModeAction(true)),
            );
          }

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

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