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

import { GET_CONTENT_OWNERS_OPTIONS } from '@/graphql/services/users/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/contentOwners';

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

const query = `
  query ${GET_CONTENT_OWNERS_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_CONTENT_OWNERS_OPTIONS}(payload: $payload) {
      id
      name
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_CONTENT_OWNERS_OPTIONS].map((account) => ({
    ...account,
    value: account.id,
    label: account.name,
  }));

export default (action$) =>
  action$.pipe(
    ofType(getContentOwnersOptionsAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            searchText: action.payload,
            pageSize: 30,
          },
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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

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