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

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

import { PAYLOAD_NAME } from '../../../../../graphql/services/contentOwners/types/payload/bulkActionDisableOrActive';

import * as selectors from '../selectors';
import { bulkDisableOrActiveAction, getDataAction, setTableAction } from '../slices';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ${BULK_ACTION_DISABLE_OR_ACTIVE} ($payload: ${PAYLOAD_NAME}) {
    ${BULK_ACTION_DISABLE_OR_ACTIVE}(payload: $payload) {
      ids
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(bulkDisableOrActiveAction.type),
    filter(() => {
      const selected = selectors.selectedSelector(state$.value);

      return selected.length > 0;
    }),
    switchMap((action) => {
      const selected = selectors.selectedSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            ids: selected,
            status: action.payload,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                notifyAction({
                  type: TYPE_SUCCESS,
                  message: 'Action completed successfully',
                }),
              ),
              of(
                setTableAction({
                  selected: [],
                }),
              ),
              of(getDataAction()),
            );
          }

          return EMPTY;
        }),
      );

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