import { ofType } from 'redux-observable';
import { concat, Observable, of } from 'rxjs';
import { exhaustMap, filter, switchMap } from 'rxjs/operators';
import type { Action } from '@reduxjs/toolkit';

import { UserType } from '@/modules/@common/user/types';

import { getUserDataAction, setUserDataAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import { logOutEventAction } from '@/modules/@common/token/redux/slices';

import { userInit as userQuery } from '../../../gql/queries';

const getResponse = ({ data: { user } }: { data: { user: UserType } }) => user;

export default (action$: Observable<Action>) =>
  action$.pipe(
    ofType(getUserDataAction.type),
    filter(() => !!getToken()),
    exhaustMap(() =>
      gqlRequest({
        query: userQuery,
      }).pipe(
        switchMap((data) => {
          const response = getResponse(data);

          const actions = [];

          if (response) {
            actions.push(of(setUserDataAction(response)));
          } else {
            actions.push(of(logOutEventAction()));
          }

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