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

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

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

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

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

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

          if (!response.errors.length) {
            const aiPlaylist = getResponse(response);

            actions.push(of(setAiPlaylistAction({ [aiPlaylist.type]: aiPlaylist })));
          }

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

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