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

import { TARGETING_STATUS_TYPES } from '../../constants';

import { changeTargetingStatusesAction, getTargetingAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ChangeVideoTargetingStatuses(
    $videoId: String
    $site: [String]
    $statusType: String
    $statusValue: String
  ) {
    changeVideoTargetingStatuses(
      videoId: $videoId
      site: $site
      statusType: $statusType
      statusValue: $statusValue
    ) {
      targetingStatus
      adPlaybackStatus
      budgetControlStatus
    }
  }
`;

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

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

      const variables = {
        videoId,
        site,
        statusType,
        statusValue,
      };

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

            actions.push(
              of(
                setStateAction({
                  targetingStatus,
                  adPlaybackStatus,
                }),
              ),
            );

            if (statusType === TARGETING_STATUS_TYPES.budgetControlStatus) {
              actions.push(
                of(
                  getTargetingAction({
                    videoId,
                    site,
                  }),
                ),
              );
            }

            return concat(...actions);
          }

          return EMPTY;
        }),
      );

      return concat(of(setStateAction({ isLoading: true })), stream$, of(setStateAction({ isLoading: false })));
    }),
  );
