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

import { TEMPLATE_CATEGORIES_OPTIONS } from '@/modules/forms/constants';

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

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

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

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

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  templateCategoryOptions: [].concat(TEMPLATE_CATEGORIES_OPTIONS, getResponse(response)),
                }),
              ),
            );
          }

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

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