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 { getAdvertiserOptions, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import type { GraphQLResponse } from '@/modules/@common/store/helpers';

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

export type RequestPayloadType = {
  searchText?: string;
  pageSize: number;
  siteIds?: number[];
};

type ResponseType = {
  data: {
    id: string;
    name: string;
  }[];
};

type ActionPayload = {
  searchText: string;
};

const queryName = 'videoUploadGetAdvertiserOptions' as const;

const getResponse = (data: ResponseType) => data.data;

const query = `
  query VideoUploadGetAdvertiserOptions(
    $pageSize: Int,
    $searchText: String,
  ) {
    ${queryName}(
      pageSize: $pageSize,
      searchText: $searchText,
    ) {
      data {
        id
        name
        logo
      }
    }
  }
`;

const getSupplyTagOptionsEpic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getAdvertiserOptions> => action.type === getAdvertiserOptions.type),
    debounce((action) => {
      if (!action.payload) {
        return timer(0);
      }
      const { searchText = '' } = action.payload;
      return timer(searchText.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actionPayload = action.payload! as ActionPayload;
      const payload: RequestPayloadType = {
        searchText: actionPayload.searchText || '',
        pageSize: 500,
      };

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

export default getSupplyTagOptionsEpic;
