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

import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

import * as selectors from '../selectors';
import { setIsSearchLoadingAction, setSearchAction, setSearchResultAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query supplyDemandTagSearch(
    $query: String,
    $size: Int,
    $searchSupply: Boolean,
    $searchDemand: Boolean,
    $siteIds: [String],
    $daccountIds: [MarketplaceValueInputType]
  ) {
    supplyDemandTagSearch(
      query: $query,
      size: $size,
      searchSupply: $searchSupply,
      searchDemand: $searchDemand,
      siteIds: $siteIds,
      daccountIds: $daccountIds
    ) {
      data {
        id
        daccountId
        advertiserId
        accountId
        siteId
        name
        groupName
        status
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(setSearchAction.type),
    debounceTime(100),
    filter(() => !!getToken()),
    switchMap((action) => {
      const userPermissions = getUserPermissionsSelector(state$.value);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      const { search } = action.payload;

      const state = state$.value;

      const userDemandAccounts = selectors.userDemandAccountsSelector(state);
      const userHubs = selectors.userHubsSelector(state);

      let filters = {};

      if (search.length <= 1) {
        return of(setSearchResultAction([]));
      }

      if (!isAdminMP) {
        filters = {
          ...filters,
          siteIds: userHubs.filter((item) => item.mpSelfService).map((item) => item.id?.toString()),
          daccountIds: userDemandAccounts.map((item) => ({ value: item.id?.toString() })),
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          query: search,
          size: 50,
          searchSupply: true,
          searchDemand: true,
          ...filters,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setSearchResultAction(data.supplyDemandTagSearch?.data ?? [])));
          }

          return concat(...actions, of(setIsSearchLoadingAction(false)));
        }),
      );

      return concat(of(setIsSearchLoadingAction(true)), stream$);
    }),
  );
