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

import { getCountriesListAction, setAdvertiserSettingsTabAction, setTargetingTabAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$) =>
  action$.pipe(
    ofType(getCountriesListAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];
          const countriesList =
            data.commonGeography?.map((geo) => ({
              label: geo.name,
              value: geo.uiKey,
            })) ?? [];

          if (!errors.length) {
            actions = [
              of(
                setTargetingTabAction({
                  countriesList,
                }),
              ),
              of(
                setAdvertiserSettingsTabAction({
                  countriesList,
                }),
              ),
            ];
          }

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

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