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

import { getTemplatePlayerOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query hubsTemplatePlayers(
    $searchText: String,
    $pageSize: Int,
    $type: Int,
    $accountId: Int,
  ) {
    hubsTemplatePlayers(
      searchText: $searchText,
      pageSize: $pageSize,
      type: $type, 
      accountId: $accountId,
    ) {
      id
      name
    }
  }
`;

const getResponse = ({ data: { hubsTemplatePlayers } }) =>
  hubsTemplatePlayers.map((player) => ({
    value: player.id,
    label: player.name,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getTemplatePlayerOptionsAction.type),
    switchMap((action) => {
      const { searchText = '', type = null, accountId = null } = action.payload ?? {};

      const stream$ = gqlRequest({
        query,
        variables: {
          searchText,
          pageSize: 30,
          type,
          accountId,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const templatePlayerOptions = getResponse(response);

            actions.push(
              of(
                setAction({
                  templatePlayerOptions,
                }),
              ),
            );
          }

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

      return concat(
        of(
          setAction({
            templatePlayerOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
