import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { delay, filter, mapTo, switchMap } from 'rxjs/operators';

import { PublishEntryType } from '../../types';

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

import type { RootState } from '@/modules/@common/store/store';

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

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getPublishEntriesAction> => action.type === getPublishEntriesAction.type,
    ),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoIds: [action.payload],
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const publishEntries: PublishEntryType[] = data.searchPublishEntries?.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$);
    }),
  );

export default epic;
