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

import { typeSelector } from '../selectors';
import { getViewabilityConfigAction, setViewabilityConfigAction, updateDestinationFormAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getPublishViewabilityConfig {
    getPublishViewabilityConfig {
      mediaPlatform
      viewabilities {
        name
        onlyForExisting
      }
      transitions {
        name
        transitions
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getViewabilityConfigAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({ query: queryGQL }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const destinationId = action.payload;
            const type = typeSelector(state$.value);

            actions.push(of(setViewabilityConfigAction(data.getPublishViewabilityConfig)));

            if (!destinationId && type) {
              actions.push(
                of(
                  updateDestinationFormAction({
                    visibility: data.getPublishViewabilityConfig.find((config) => config.mediaPlatform === type)
                      .viewabilities[0].name,
                  }),
                ),
              );
            }
          }

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

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