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

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

const query = `
  query customReports(
    $pageSize: Int,
    $page: Int,
    $sortBy: String,
    $sortOrder: String,
    $searchText: String,
    $searchIn: [String]
  ) {
    customReports(
      pageSize: $pageSize,
      page: $page,
      sortBy: $sortBy,
      sortOrder: $sortOrder,
      searchText: $searchText,
      searchIn: $searchIn
    ) {
      page
      pageSize
      recordsTotal
      records {
        id
        name
        scheduled
        scheduleType
        scheduleValue {
          dayInWeek
          dayInMonth
          time
        }
        period
        periodCustomStartDate
        periodCustomEndDate
        lastDelivery
        nextDelivery
        updatedBy
        createdBy
        updatedAt
        createdAt
      }
    }
  }
`;

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

      const searchText = selectors.searchTextSelector(state);
      const page = selectors.pageSelector(state);
      const pageSize = selectors.pageSizeSelector(state);
      const sortBy = selectors.sortBySelector(state);
      const sortOrder = selectors.sortOrderSelector(state);

      let requestParams = {
        page,
        pageSize,
      };

      if (searchText?.length) {
        requestParams = {
          ...requestParams,
          searchText,
        };
      }

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

      const stream$ = gqlRequest({
        query,
        variables: {
          searchIn: ['name', 'createdBy'],
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { records, recordsTotal } = data.customReports;
            actions.push(of(setFieldAction({ records, recordsTotal })));
          }
          return concat(...actions);
        }),
      );

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