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

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

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

const gqlQuery = `
  query ${GET_ITEM} {
    ${GET_ITEM} {
      overallFailure
      popup
      message
      updatedAt
      updatedBy
    }
  }
`;

const getResponse = ({ data }) => {
  const notification = data[GET_ITEM];
  return {
    ...notification,
    overallFailure: !!notification.overallFailure,
    popup: !!notification.popup,
  };
};

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap(() => {
      const stream$ = gqlRequest(
        {
          query: gqlQuery,
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
