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

import { responseToTableRow } from '../../helpers';
import { getTargetingAction, getTargetingStatusesAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetVideoTargeting(
    $videoId: String
    $site: [String]
  ) {
    getVideoTargeting(
      videoId: $videoId
      site: $site
    ) {
      data {
        uid
        startDateTime
        endDateTime
        status
        device
        geo {
          geo,
          action
        }
        viewsBudget
        viewsDelivered
        pacing
      }
      totalCount
    }
    commonGeography {
      id
      uiKey
      name
    }
  }
`;

const getResponse = ({ data: { getVideoTargeting, commonGeography } }) => ({ getVideoTargeting, commonGeography });

export default (action$) =>
  action$.pipe(
    ofType(getTargetingAction.type),
    switchMap((action) => {
      const { videoId, site } = action.payload;

      const variables = {
        videoId,
        site,
      };

      const stream$ = gqlRequest({
        query,
        variables,
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const { getVideoTargeting, commonGeography } = getResponse(response);
            const countryOptions = commonGeography.map((geo) => ({
              label: geo.name,
              value: geo.uiKey,
            }));
            const data = getVideoTargeting.data.map(responseToTableRow({ countryOptions }));

            return concat(
              of(
                setStateAction({
                  data: data.reverse(),
                  totalCount: getVideoTargeting.totalCount,
                  countryOptions,
                }),
              ),
              of(
                getTargetingStatusesAction({
                  videoId,
                  site,
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

      return concat(of(setStateAction({ isLoading: true })), stream$, of(setStateAction({ isLoading: false })));
    }),
  );
