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

import { playlistsSelector } from '../../selectors';
import { setAiPlaylistAction, updateAiPlaylistAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

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

const getResponse = ({ data: { updateEditorialAiPlaylist: aiPlaylist } }) => aiPlaylist;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateAiPlaylistAction.type),
    debounceTime(+process.env.APP_CLEAR_TIMEOUT),
    filter(() => !!getToken()),
    switchMap((action) => {
      const { playlistId, aiPlaylistId, length } = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          editorialPlaylistId: playlistId,
          aiPlaylistId,
          length,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const playlists = playlistsSelector(state$.value);
            const playlist = playlists.find((playlist$) => playlist$.id === playlistId);
            const aiPlaylist = Object.values(playlist.aiPlaylists).find(
              (aiPlaylist$) => aiPlaylist$.id === aiPlaylistId,
            );

            const updatedAiPlaylist = { ...aiPlaylist, length: getResponse(response).length };

            actions.push(of(setAiPlaylistAction({ playlistId, aiPlaylist: updatedAiPlaylist })));
          }

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

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