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

import { SORT_ASC } from '@/modules/@common/constants/sort';

import { getUsersByAccountAction, setIsLoadingAction, setUsersByAccountAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query accessGetUsersByAccount(
    $searchText: String,
    $searchIn: [String],
    $page: Int,
    $pageSize: Int,
    $sortOrder: String,
    $sortBy: String,
    $videoId: String!
  ) {
    accessGetUsersByAccount(
      searchText: $searchText,
      searchIn: $searchIn,
      page: $page,
      pageSize: $pageSize,
      sortOrder: $sortOrder, 
      sortBy: $sortBy,
      videoId: $videoId
    ) {
      records {
        id
        email
        firstName
        lastName
      }  
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getUsersByAccountAction.type),
    debounce((action) => timer(action.payload?.searchText?.length ? 500 : 0)),
    switchMap((action) => {
      const selected = action.payload?.selected ?? 0;
      const variables = {
        searchText: action.payload?.searchText ?? '',
        searchIn: ['firstName', 'lastName', 'email'],
        page: 1,
        status: 1,
        pageSize: 10 + selected,
        sortBy: 'firstName',
        sortOrder: SORT_ASC,
        videoId: action.payload.videoId,
      };

      const stream$ = gqlRequest({
        query,
        variables,
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setUsersByAccountAction(data.accessGetUsersByAccount.records)));
          }

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

      return concat(of(setIsLoadingAction(true)), stream$, of(setIsLoadingAction(false)));
    }),
  );
