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

import { responseToTableRow, rowToRequestBody } from '../../helpers';
import * as selectors from '../selectors';
import { createTargetingAction, getTargetingStatusesAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createTargetingAction.type),
    switchMap((action) => {
      const data = selectors.data(state$.value);
      const countryOptions = selectors.countryOptions(state$.value);
      const budgetControlStatus = selectors.budgetControlStatus(state$.value);
      const { videoId, site, row } = action.payload;
      const targeting = rowToRequestBody(row, budgetControlStatus);

      const stream$ = gqlRequest({
        query,
        variables: {
          videoId,
          site,
          targeting,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const newRow = responseToTableRow({ countryOptions })(getResponse(response));
            const dataForUpdate = [].concat([newRow], data);

            return concat(
              of(
                setStateAction({
                  data: dataForUpdate,
                  lastCreatedIdForOpenEdit: newRow.id,
                }),
              ),
              of(
                getTargetingStatusesAction({
                  videoId,
                  site,
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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