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 getAiPlaylist(
    $watchId: Int!,
    $channelId: Int!,
    $aiPlaylistId: String!
  ) {
    getAiPlaylist(
      watchId: $watchId,
      channelId: $channelId,
      aiPlaylistId: $aiPlaylistId
    ) {
      id
      type
      length
    }
  }
`;

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

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

          if (!errors.length) {
            actions.push(
              of(setAiPlaylistAction({ [data.getAiPlaylist.type]: data.getAiPlaylist })),
              of(getAiFiltersAction({ watchId, channelId, aiPlaylistId: +aiPlaylistId })),
            );
          }

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

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