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

import { UPDATE_SSO_ITEM } from '@/graphql/services/sso/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';
import { PROVIDER_VALUE_GOOGLE } from '@/modules/sso/List/constants';

import { PAYLOAD_UPSERT_SSO_ITEM } from '@/graphql/services/sso/types/payload/ssoUpsertItem';

import * as selectors from '../selectors';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import normalizeCustomAttributes from '@/modules/sso/Editor/helpers/normalizeCustomAttributes';

const query = `mutation ${UPDATE_SSO_ITEM}($payload: ${PAYLOAD_UPSERT_SSO_ITEM}) {
  ${UPDATE_SSO_ITEM}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap((action) => {
      const displayName = selectors.displayNameSelector(state$.value);
      const allDomains = selectors.allDomainsSelector(state$.value);
      const allHubs = selectors.allHubsSelectors(state$.value);
      const domains = selectors.domainsSelector(state$.value);
      const onlyExisting = selectors.onlyExistingSelector(state$.value);
      const provider = selectors.providerSelector(state$.value);
      const ssoDefaultHubs = selectors.ssoDefaultHubsSelector(state$.value);
      const ssoCustomAttributes = selectors.ssoCustomAttributesSelector(state$.value);
      const metadataURL = selectors.metadataURLSelector(state$.value);

      const payload = {
        id: action.payload,
        displayName,
        allDomains,
        allHubs,
        domains: allDomains ? [] : domains,
        onlyExisting,
        provider,
        ssoDefaultHubs: allHubs ? [] : ssoDefaultHubs,
        ssoCustomAttributes: normalizeCustomAttributes(ssoCustomAttributes),
      };

      if (provider !== PROVIDER_VALUE_GOOGLE) {
        payload.metadataURL = metadataURL;
      }

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

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Updated',
              }),
            );
          }

          return EMPTY;
        }),
      );

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