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

import { getCategoryOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getFormTemplateCategories(
    $pageSize: Int,
  ) {
    getFormTemplateCategories(
      pageSize: $pageSize,
    ) {
      records {
        id
        name
      }  
    }
  }
`;

const getResponse = ({ data: { getFormTemplateCategories } }) =>
  getFormTemplateCategories.records.map((cat) => ({
    value: cat.id,
    label: cat.name,
  }));

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

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

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

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