import { type Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';
import type { Action } from '@reduxjs/toolkit';

import { getCountriesFullListAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query commonGeography {
    commonGeography {
      id
      uiKey
      name
    }
  }
`;

const epic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter(
      (action): action is ReturnType<typeof getCountriesFullListAction> =>
        action.type === getCountriesFullListAction.type,
    ),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        variables: {},
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(
              of(
                setAction({
                  countriesFullList: data?.commonGeography ?? [],
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

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

export default epic;
