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

import * as selectors from '../selectors';
import { searchAvailableKeysAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query availableKeysSearch(
    $from: Int,
    $size: Int,
    $query: String,
    $status: String,
    $sortBy: String,
    $sortOrder: String
  ) {
    availableKeysSearch(
      from: $from,
      size: $size,
      query: $query,
      status: $status,
      sortBy: $sortBy,
      sortOrder: $sortOrder
    ) {
      totalCount
      data {
        id
        created
        updated
        name
        key
        count
        status
        updatedBy
        user
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(searchAvailableKeysAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap(() => {
      const state = state$.value;

      const search = selectors.searchSelector(state);
      const page = selectors.pageSelector(state);
      const rowsPerPage = selectors.rowsPerPageSelector(state);
      const status = selectors.statusSelector(state);
      const sortBy = selectors.sortBySelector(state);
      const sortOrder = selectors.sortOrderSelector(state);

      let requestParams = {};

      if (search?.length) {
        requestParams = {
          ...requestParams,
          query: search,
        };
      }

      if (status !== 'ALL') {
        requestParams = {
          ...requestParams,
          status,
        };
      }

      if (sortBy) {
        requestParams = {
          ...requestParams,
          sortBy,
          sortOrder,
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          size: rowsPerPage || 10,
          from: (page || 0) * (rowsPerPage || 10),
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { data: keyLists, totalCount } = data.availableKeysSearch;

            actions.push(
              of(
                setFieldAction({
                  totalCount,
                  keyLists,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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