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

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

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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(updateTargetingAction.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,
          },
        },
        {
          mapError: mapApiError(),
        },
      ).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const newRow = responseToTableRow({ countryOptions })(getResponse(response));
            const dataForUpdate = data.map((oldRow) => (oldRow.id === row.id ? newRow : oldRow));

            return concat(
              of(setStateAction({ data: dataForUpdate })),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Targeting updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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