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

import { UPDATE_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 { buildUpdateRequestBody } from '../../helpers/buildRequestBody';
import { subdomainSelector } from '../selectors';
import { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

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

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

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

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

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