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

import { ALL_HUB_OPTION } from '../../constants';
import { GET_SSO_ITEM } from '@/graphql/services/sso/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { PAYLOAD_GET_SSO_ITEM } from '@/graphql/services/sso/types/payload/ssoGetItem';

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

const query = `
  query ${GET_SSO_ITEM}($payload: ${PAYLOAD_GET_SSO_ITEM}) {
    ${GET_SSO_ITEM}(payload: $payload) {
      displayName  
      allDomains
      allHubs
      onlyExisting
      domains
      metadataURL
      provider
      ssoCustomAttributes {
        id
        allHubs
        name
        status
        ssoCustomAttributesHubs {
          id
          name
        }
        ssoCustomAttributesKeys
      }
      ssoDefaultHubs {
        id
        name
      }
      settings {
        allDomainsDisabled
        cannotCreateProfile
        singleSignOnUrl
        audienceUri
      } 
    }
  }
`;

const getResponse = ({ data }) => {
  const item = data[GET_SSO_ITEM];

  return item;
};

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const payload = {};

      if (action.payload.provider) {
        payload.provider = action.payload.provider;
      }

      if (action.payload.id) {
        payload.id = action.payload.id;
      }

      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload,
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

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

            Router.push('/sso');
          } else {
            const res = getResponse(response);
            const data = action.payload.id ? res : { settings: res.settings, provider: action.payload.provider };

            if (res.settings.allDomainsDisabled) {
              data.allDomains = false;
            }

            if (res.allHubs) {
              data.ssoDefaultHubs = [ALL_HUB_OPTION];
            }

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

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

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