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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

const query = `
  mutation DeletePlayer($id: Int!) {
    deletePlayer(id: $id){
      id
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(deletePlayerAction.type),
    switchMap(({ payload: { id } }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [];
          if (!errors.length) {
            actions.push(of(getDataAction()));
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Player was deleted successfully',
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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