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

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

const categoryEnum = {
  [getBrandSafetyOptionsAction.type]: 'BRAND_SAFETY',
};

const query = `
 query autocompleteKeyword(
   $contentOwner: [Float],
   $category: String!,
   $prefix: String,
   $excludeOrigin: String,
   $checkBrandSafetyPermission: Boolean
  ) {
    autocompleteKeyword(
      contentOwner: $contentOwner,
      category: $category,
      prefix: $prefix,
      excludeOrigin: $excludeOrigin,
      checkBrandSafetyPermission: $checkBrandSafetyPermission
    ) {
      value
    }
  }
`;

const getResponse = ({ data: { autocompleteKeyword } }) =>
  autocompleteKeyword.map(({ value }) => ({ value, label: value }));

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

      const stream$ = gqlRequest({
        query,
        variables: {
          contentOwner: getUserContentOwnerIdsSelector(state$.value),
          category: categoryEnum[action.type],
          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$,
      );
    }),
  );
