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

import * as selectors from '../selectors';
import { getLabelOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserAccountIdSelector } from '@/modules/@common/user/redux/selectors';

const query = `
 query autocompleteLabelGrouped(
   $accountId: Int,
   $prefix: String!,
   $excludeOrigin: String
  ) {
    autocompleteLabelGrouped(
      accountId: $accountId,
      prefix: $prefix,
      excludeOrigin: $excludeOrigin
    ) {
      labelGrouped {
        name
        values {
          value
        }
        color
        contentOwnerId
        labelId
        accountId
      }
    }
  }
`;

const getResponse = ({
  data: {
    autocompleteLabelGrouped: { labelGrouped },
  },
}) =>
  labelGrouped.reduce((acc, curr) => {
    const labels = curr.values
      ? curr.values.map((label) => ({
          label: label.value,
          value: label.value,
          name: curr.name,
          color: curr.color,
          contentOwner: curr.contentOwner,
          accountId: curr.accountId,
          groupBy: `${curr.name}|${curr.labelId}|${curr.color}`,
          labelId: curr.labelId,
        }))
      : [];

    return [...acc, ...labels];
  }, []);

export default (action$, state$) =>
  action$.pipe(
    ofType(getLabelOptionsAction.type),
    debounce((action) => timer(action.payload?.length ? 1000 : 0)),
    switchMap((action) => {
      const autocomplete = selectors.autocompleteSelector(state$.value);
      const userAccountId = getUserAccountIdSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          accountId: userAccountId ? parseInt(userAccountId, 10) : null,
          prefix: action.payload ?? '',
          excludeOrigin: 'RSS',
          checkBrandSafetyPermission: false,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions: getResponse(response),
                  },
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
