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

import { GET_DEPARTMENT_OPTIONS } from '@/graphql/services/users/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/departmentList';

import { getDepartmentOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query ${GET_DEPARTMENT_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_DEPARTMENT_OPTIONS}(payload: $payload) {
      id
      name
    }
  }
`;

const getResponse = ({ data }) =>
  data[GET_DEPARTMENT_OPTIONS].map((account) => ({
    value: account.id,
    label: account.name,
  }));

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

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

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

      return concat(
        of(
          setAction({
            departmentOptions: null,
          }),
        ),
        stream$,
      );
    }),
  );
