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

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

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

import { createDepartmentAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import * as selectors from '@/modules/users/Editor/redux/selectors';

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

const getResponse = ({ data }) => data[CREATE_DEPARTMENT];

export default (action$, state$) =>
  action$.pipe(
    ofType(createDepartmentAction.type),
    switchMap(({ payload }) => {
      const account = selectors.accountSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            accountId: account.id,
            name: payload,
          },
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

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

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

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