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

import { getTargetingStatusesAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { videosAction } from '@/modules/editorial/editorialSearchResults/redux/slices';

const query = `
  query GetVideoTargetingStatuses(
    $videoId: String
    $site: [String]
  ) {
    getVideoTargetingStatuses(
      videoId: $videoId
      site: $site
    ) {
      targetingStatus
      adPlaybackStatus
      budgetControlStatus
    }
  }
`;

const getResponse = ({ data: { getVideoTargetingStatuses } }) => getVideoTargetingStatuses;

export default (action$, state$) =>
  action$.pipe(
    ofType(getTargetingStatusesAction.type),
    switchMap((action) => {
      const { videoId, site } = action.payload;

      const variables = {
        videoId,
        site,
      };

      const stream$ = gqlRequest({
        query,
        variables,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const { targetingStatus, adPlaybackStatus, budgetControlStatus } = getResponse(response);

            // add targeting status to video list
            const videos = videosSelector(state$.value);
            const updatedVideoList = videos.map((video) => {
              const updatedVideo = { ...video };
              if (updatedVideo.uid === videoId) {
                updatedVideo.targetingStatus = targetingStatus;
              }
              return updatedVideo;
            });

            return concat(
              of(
                setStateAction({
                  targetingStatus,
                  adPlaybackStatus,
                  budgetControlStatus,
                }),
              ),
              of(videosAction(updatedVideoList)),
            );
          }

          return EMPTY;
        }),
      );

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