import Router from 'next/router';
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 { ITEM_INPUT_TYPE_NAME } from '../../../../../graphql/services/adsServers/types/input/itemCreate';

import {
  commentsSelector,
  isDefaultForPlayerTypeSelector,
  macroSelector,
  nameSelector,
  playerTypesIdsSelector,
  statusSelector,
  urlSelector,
} from '../selectors';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
mutation updateAdServersPCN($entity: ${ITEM_INPUT_TYPE_NAME}) {
  updateAdServersPCN(entity: $entity) { 
    id
  } 
}
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const name = nameSelector(state$.value);
      const status = statusSelector(state$.value);
      const url = urlSelector(state$.value);
      const isDefaultForPlayerType = isDefaultForPlayerTypeSelector(state$.value);
      const playerTypesIds = playerTypesIdsSelector(state$.value);
      const macro = macroSelector(state$.value);
      const comments = commentsSelector(state$.value);

      const entity = {
        id: action.payload,
        name,
        status,
        url,
        isDefaultForPlayerType,
        playerTypesIds: isDefaultForPlayerType ? playerTypesIds : [],
        macro,
        comments,
      };

      const stream$ = gqlRequest({
        query,
        variables: {
          entity,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/ad-servers');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Ad Server updated',
              }),
            );
          }

          return EMPTY;
        }),
      );

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