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

import { parseResponseToState } from '../../helpers';
import { getRulesAction, setModuleStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetUserRules($status: Int) {
    getUserRules(
      status: $status
    ) {
      rules {
        ruleId
        ruleName
        ruleOrder
        sharedVideoRules {
          allMyVideo {
            value
            order
          }
          sources {
            value {
              id
              name
            }
            order
            condition
          }
          labels {
            value
            order
            condition
          }
          wordsInTitle {
            value
            order
            condition
          }
        }
        shareWith {
          allRelatedUsers {
            value
            order
          }
          users {
           value {
            id
            email
            firstName
            lastName
           }
           order
          }
          hubs {
            value {
              id
              name
            }
            order
          }
        }
      }
    }
  }
`;

const getResponse = ({ data: { getUserRules } }) => getUserRules.rules;

export default (action$) =>
  action$.pipe(
    ofType(getRulesAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        variables: {
          status: 1,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const res = getResponse(response);
            const rulesState = parseResponseToState(res);
            return of(
              setModuleStateAction({
                rules: rulesState,
              }),
            );
          }

          return EMPTY;
        }),
      );

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