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

import { SAVE_ITEM } from '../../../../graphql/services/notifications/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_ITEM } from '../../../../graphql/services/notifications/types/payload/item';

import * as selectors from '../selectors';
import { saveItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const gqlQuery = `
  mutation ${SAVE_ITEM} ($payload: ${PAYLOAD_ITEM}) {
    ${SAVE_ITEM}(payload: $payload) {
      overallFailure
      popup
      message
      updatedAt
      updatedBy
    }
  }
`;

const getResponse = ({ data }) => {
  const response = data[SAVE_ITEM];

  return {
    ...response,
    overallFailure: !!response.overallFailure,
    popup: !!response.popup,
  };
};

export default (action$, state$) =>
  action$.pipe(
    ofType(saveItemAction.type),
    switchMap(() => {
      const overallFailure = selectors.overallFailureSelector(state$.value);
      const popup = selectors.popupSelector(state$.value);
      const message = selectors.messageSelector(state$.value);

      const stream$ = gqlRequest({
        query: gqlQuery,
        variables: {
          payload: {
            overallFailure: overallFailure ? 1 : 0,
            popup: popup ? 1 : 0,
            message,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const actions = [
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Saved',
                }),
              ),
              of(
                setAction({
                  ...getResponse(response),
                }),
              ),
            ];
            return concat(...actions);
          }

          return EMPTY;
        }),
      );

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