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

import { CREATE_ACCOUNT } from '@/graphql/services/accounts/constants';
import { TYPE_ERROR, TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/accounts/types/payload/item';

import { buildCreateRequestBody } from '../../helpers/buildRequestBody';
import { salesforceIdSelector, subdomainSelector } from '../selectors';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `mutation ${CREATE_ACCOUNT}($payload: ${PAYLOAD_NAME}) {
  ${CREATE_ACCOUNT}(payload: $payload) {
    id
  }
}`;

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap(({ payload }) => {
      const body = buildCreateRequestBody(state$.value);
      const salesforceId = salesforceIdSelector(state$.value);
      const subdomain = subdomainSelector(state$.value);

      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id: payload,
              ...body,
            },
          },
        },
        { showNotificationMessage: false },
      ).pipe(
        switchMap((response) => {
          const error = response.errors?.[0];

          if (!error) {
            Router.push('/accounts');
            return of(showNotificationAction({ type: TYPE_SUCCESS, message: 'Account created' }));
          }

          const message =
            error?.response?.status === 409
              ? `An Account with Salesforce Account Id 
              ${salesforceId} ${subdomain ? `or with Subdomain ${subdomain}` : ''} already exists`
              : "Can't create account";

          return of(
            showNotificationAction({
              type: TYPE_ERROR,
              message,
            }),
          );
        }),
      );

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