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

import { ARCHIVE_XRAY_LINE_ITEM } from '@/graphql/services/xRayLineItems/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/xRayLineItems/types/payload/archive';

import { archiveAction, getDataAction } from '../slices';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$) =>
  action$.pipe(
    ofType(archiveAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: { id: action.payload },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                notifyAction({
                  type: TYPE_SUCCESS,
                  message: 'Archived',
                }),
              ),
              of(getDataAction()),
            );
          }

          return EMPTY;
        }),
      );

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