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

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

import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query getAdServerPCNById(
    $id: Int!
  ) {
    getAdServerPCNById(
      id: $id
    ) {
      id
      name
      status
      url
      placementId
      isDefaultForPlayerType
      playerTypesIds
      macro
      comments
    }
  }
`;

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

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            id: action.payload.id,
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open dashboard for edit",
                }),
              ),
            );

            Router.push('/ad-servers');
          } else {
            const data = getResponse(response);

            actions.push(of(setAction(data)));
          }

          return concat(...actions);
        }),
      );

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