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

import { getPublishEntriesAction, setPublishEntriesAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query videoSearchPublishEntries($videoIds: [String]) {
    videoSearchPublishEntries(videoIds: $videoIds) {
      totalCount
      data {
        id
        name
        videoId
        accountId
        platform
        publishedVideoId
        status
        viewability
        postText
        target {
          id
          type
          name
        }
        settings {
          sync
          type
        }
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPublishEntriesAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoIds: [action.payload],
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const publishEntries = data.videoSearchPublishEntries?.data;

            actions.push(of(setPublishEntriesAction(publishEntries)));

            if (publishEntries?.find((entry) => entry.status === 'PROCESSING')) {
              actions.push(of(null).pipe(mapTo(getPublishEntriesAction(action.payload)), delay(4000)));
            }
          }

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

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