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

import { getAiFiltersAction, getAiPlaylistAction, setAiPlaylistAction } from '../../slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$) =>
  action$.pipe(
    ofType(getAiPlaylistAction.type),
    concatMap((action) => {
      const { playlistId, aiPlaylistId } = action.payload;

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

          if (!errors.length && data.getEditorialAiPlaylist) {
            actions.push(of(setAiPlaylistAction({ playlistId, aiPlaylist: data.getEditorialAiPlaylist })));
            actions.push(of(getAiFiltersAction({ playlistId, aiPlaylistId })));
          }

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

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