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

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

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

const query = `
  query ${GET_USER_TIMEZONE_OPTIONS} {
    ${GET_USER_TIMEZONE_OPTIONS} {
      name
      displayName
    }
  }
`;

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

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

          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  timezoneOptions: getResponse(response),
                }),
              ),
            );
          }

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

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