import type { Action } from 'redux';
import type { Epic } from 'redux-observable';
import { EMPTY, of, timer } from 'rxjs';
import { debounce, filter, switchMap } from 'rxjs/operators';

import { GET_FEED_OWNERS_OPTIONS } from '@/graphql/services/feeds/constants';

import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/owners';
import type { FeedType } from '@/modules/feeds/Editor/types';

import { accountSelector, isSelfServeUserSelector } from '../selectors';
import { getOwnersOptionsAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';
import { getUserAccountIdSelector } from '@/modules/@common/user/redux/selectors';

import type { RootState } from '@/modules/@common/store/store';

export type PayloadType = {
  searchText: string;
  pageSize: number;
  accountId: number;
};

const getResponse = (data: FeedType['accessVideoOwner'][]) => data;

const query = `
  query ${GET_FEED_OWNERS_OPTIONS}($payload: ${PAYLOAD_NAME}) {
    ${GET_FEED_OWNERS_OPTIONS}(payload: $payload) {
      id
      name
    }
  }
`;

const getAccountOptionsEpic: Epic<Action, Action, RootState> = (action$, state$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getOwnersOptionsAction> => action.type === getOwnersOptionsAction.type,
    ),
    debounce((action) => {
      const { searchText } = action.payload;
      return timer(searchText.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const isSelfServeUser = isSelfServeUserSelector(state$.value);
      const userAccountId = getUserAccountIdSelector(state$.value);
      const accountId = accountSelector(state$.value)?.id;

      const payload: PayloadType = {
        searchText: action.payload.searchText,
        pageSize: 30,
        accountId: isSelfServeUser ? +userAccountId! : accountId!,
      };

      return gqlRequest({
        query,
        variables: { payload },
      }).pipe(
        switchMap((response: GraphQLResponse<typeof GET_FEED_OWNERS_OPTIONS, FeedType['accessVideoOwner'][]>) => {
          if (!response.errors.length) {
            return of(
              setAction({
                ownersOptions: getResponse(response.data[GET_FEED_OWNERS_OPTIONS]),
              }),
            );
          }
          return EMPTY;
        }),
      );
    }),
  );

export default getAccountOptionsEpic;
