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

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

import * as selectors from '../selectors';
import { searchKeyListsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query keyListsSearch(
    $from: Int,
    $size: Int,
    $query: String,
    $status: String,
    $sortBy: String,
    $sortOrder: String,
    $daccountIds: [String]
  ) {
    keyListsSearch(
      from: $from,
      size: $size,
      query: $query,
      status: $status,
      sortBy: $sortBy,
      sortOrder: $sortOrder,
      daccountIds: $daccountIds
    ) {
      totalCount
      data {
        id
        created
        updated
        name
        keys
        count
        status
        updatedBy
        user
        daccountName
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(searchKeyListsAction.type),
    debounce((action) => timer(action.payload ? 1000 : 0)),
    switchMap(() => {
      const userPermissions = getUserPermissionsSelector(state$.value);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      const state = state$.value;

      const search = selectors.searchSelector(state);
      const page = selectors.pageSelector(state);
      const rowsPerPage = selectors.rowsPerPageSelector(state);
      const status = selectors.statusSelector(state);
      const sortBy = selectors.sortBySelector(state);
      const sortOrder = selectors.sortOrderSelector(state);
      const userDemandAccounts = selectors.userDemandAccountsSelector(state);

      let requestParams = {};

      if (search?.length) {
        requestParams = {
          ...requestParams,
          query: search,
        };
      }

      if (status !== 'ALL') {
        requestParams = {
          ...requestParams,
          status,
        };
      }

      if (sortBy) {
        requestParams = {
          ...requestParams,
          sortBy,
          sortOrder,
        };
      }

      if (!isAdminMP) {
        requestParams = {
          ...requestParams,
          daccountIds: userDemandAccounts.map((item) => item.id?.toString()),
        };
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          size: rowsPerPage || 10,
          from: (page || 0) * (rowsPerPage || 10),
          ...requestParams,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { data: keyLists, totalCount } = data.keyListsSearch;

            actions.push(
              of(
                setFieldAction({
                  totalCount,
                  keyLists,
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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