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

import * as selectors from '../selectors';
import { getLookerUrlAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';
import { canSelectAccount } from '@/modules/analytics/general/helpers';

const query = `
  query GetGeneralAnalyticsLookerUrl(
    $reportId: String
    $salesforceId: String
  ) {
    getGeneralAnalyticsLookerUrl(
      reportId: $reportId
      salesforceId: $salesforceId
    ) {
      url  
    }
  }
`;

const getResponse = ({ data: { getGeneralAnalyticsLookerUrl } }) => getGeneralAnalyticsLookerUrl;

export default (action$, state$) =>
  action$.pipe(
    ofType(getLookerUrlAction.type),
    filter(() =>
      canSelectAccount(getUserPermissionsSelector(state$.value))
        ? !!selectors.salesforceIdSelector(state$.value)
        : !!selectors.selectedAnalyticSelector(state$.value),
    ),
    switchMap(() => {
      const state = state$.value;

      const menu = selectors.menuSelector(state);
      const selectedAnalytic = selectors.selectedAnalyticSelector(state);
      const salesforceId = selectors.salesforceIdSelector(state);

      const reportId = menu.find((o) => o.name === selectedAnalytic)?.lookerReportId;

      const stream$ = gqlRequest({
        query,
        variables: {
          reportId,
          salesforceId,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const data = getResponse(response);

            return of(
              setFieldAction({
                lookerReportUrl: data.url,
              }),
            );
          }

          return EMPTY;
        }),
      );

      return concat(of(setFieldAction({ isLoadingUrl: true })), stream$);
    }),
  );
