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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { responseToTableRow } from '../../helpers';
import * as selectors from '../selectors';
import { getTargetingStatusesAction, runActionTargetingAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation runActionVideoTargeting(
    $videoId: String
    $id: String
    $site: [String]
    $action: String,
  ) {
    runActionVideoTargeting(
      videoId:$videoId
      id: $id
      site: $site
      action: $action
    ) {
      uid
      startDateTime
      endDateTime
      status
      device
      geo {
        geo,
        action
      }
      viewsBudget
      viewsDelivered
      pacing
    }
  }
`;

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

export default (action$, state$) =>
  action$.pipe(
    ofType(runActionTargetingAction.type),
    switchMap((action) => {
      const data = selectors.data(state$.value);
      const countryOptions = selectors.countryOptions(state$.value);
      const { videoId, site, id, action: targetingAction } = action.payload;

      const stream$ = gqlRequest({
        query,
        variables: {
          videoId,
          id,
          site,
          action: targetingAction,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const newRow = responseToTableRow({ countryOptions })(getResponse(response));
            const dataForUpdate = data.map((oldRow) => (oldRow.id === id ? newRow : oldRow));

            return concat(
              of(setStateAction({ data: dataForUpdate })),
              of(
                getTargetingStatusesAction({
                  videoId,
                  site,
                }),
              ),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Action success',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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