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

import * as selectors from '../selectors';
import { getPricingTabAction, setPricingTabAction } from '../slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(getPricingTabAction.type),
    switchMap(() => {
      const state = state$.value;

      const info = selectors.infoSelector(state);
      const pageConfig = selectors.pageConfigSelector(state);
      const pricing = selectors.pricingSelector(state);

      const isDuplicate = pageConfig?.isDuplicate;
      const demandAccount = pageConfig?.demandAccount;
      const setPricing = {};

      setPricing.publisherDemand =
        typeof info?.publisherDemand === 'boolean' ? info?.publisherDemand : demandAccount?.publisherDemand;
      // from info for existing tag, from pageConfig(queries) for new tag

      if (info) {
        setPricing.model = info.model;
        setPricing.source = info.rateSource?.name ?? null;
        setPricing.seatId = info.rateSource?.seatId ?? '';
        setPricing.adUnitId = info.rateSource?.adUnitId ?? '';
        setPricing.type = info.rateSource?.type ?? null;
        setPricing.fixedRpmRateTable = {
          ...pricing.fixedRpmRateTable,
          rows: pricing.fixedRpmRateTable.rows,
          rowsPerPage: isDuplicate ? 100 : 5,
        };
        setPricing.additionalFeesTable = {
          ...pricing.additionalFeesTable,
          rowsPerPage: isDuplicate ? 100 : 5,
        };
        setPricing.adServingFeesTable = {
          ...pricing.adServingFeesTable,
          rowsPerPage: isDuplicate ? 100 : 5,
        };
        setPricing.adRequestFeesTable = {
          ...pricing.adRequestFeesTable,
          rowsPerPage: isDuplicate ? 100 : 5,
        };
      }

      return concat(of(setPricingTabAction(setPricing)));
    }),
  );
