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 parseResponseToState from '../../helpers/parseResponseToState';
import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query GetHubByIdQuery(
    $id: Int!
  ) {
    getHubById(
      id: $id
    ) {
      id
      account {
        id
        name
        salesforceId
      }
      demandAccountId
      demandAccount {
        id
        name
        salesforceId
      }
      mpSelfService      
      name
      publisherDomains {
        id
        domain
        players {
          id
        }
      }
      publish
      
      includePublicContent
      publisherContentOwners {
        account {
          id
          name
        }
      }
      
      selfService
      templatePlayerLumX
      templatePlayerLumXName
      templatePlayerLumXAmp
      templatePlayerLumXAmpName
      templatePlayerLumN
      templatePlayerLumNName
      templatePlayerLumNAmp
      templatePlayerLumNAmpName
      templatePlayerVertical
      templatePlayerVerticalName
      templatePlayerOutstream
      templatePlayerOutstreamName
      monetization
      firstLook
      cpm
      
      pageRefresh
      refreshIntervalMinutes
      refreshTimesLimit
      ddSpecificPublisher
      defaultRule {
        id
        publisherId
        cleanOrder
        cleanUrl
        cleanUrlRuleType
        cleanUrlRuleValue
      }
      cleanUrl {
        id
        publisherId
        cleanOrder
        cleanUrl
        cleanUrlRuleType
        cleanUrlRuleValue
      }
    }
  }
`;

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

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 = [];

          const setError = () => {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open hub for edit",
                }),
              ),
            );

            Router.push('/hubs');
          };

          if (response.errors.length) {
            setError();
          } else {
            const data = getResponse(response);
            try {
              const state = parseResponseToState(data);
              actions.push(of(setAction(state)));
            } catch {
              setError();
            }
          }

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

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