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

import {
  DEMAND_TAG_DEFAULT_TIER_VALUES,
  DEMAND_TAG_FORMAT,
  DEMAND_TAG_PRIORITY,
  DEMAND_TAG_STATUS,
  DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE,
  DEMAND_TAG_SUPPLY_CHAIN_VALUE,
  FLOOR_PRICE,
} from '../../constants';
import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

import * as selectors from '../selectors';
import { getSettingsTabAction, setSettingsTabAction } from '../slices';
import { hasPermission } from '@/modules/@common/user/helpers';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

const defineTierForDuplicate = (info, pageConfig) => {
  if (info?.priority === DEMAND_TAG_PRIORITY.firstLook) {
    return DEMAND_TAG_DEFAULT_TIER_VALUES[0].value;
  }

  return Number(info?.advertiserTier ?? pageConfig?.advertiser?.tier); // ?? info?.defaultTier;
};

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

      const info = selectors.infoSelector(state);
      const pageConfig = selectors.pageConfigSelector(state);
      const userPermissions = getUserPermissionsSelector(state);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      const setSettings = {};
      setSettings.advertiser = info?.advertiserName ?? pageConfig?.advertiser?.name;
      setSettings.demandAccount = info?.accountName ?? pageConfig?.demandAccount?.name;

      if (!(pageConfig?.isCreatingNew && !isAdminMP)) {
        // don't set tier for creating self serve demand tag
        setSettings.defaultTier = pageConfig?.isDuplicate
          ? defineTierForDuplicate(info, pageConfig)
          : (info?.defaultTier ?? Number(pageConfig?.advertiser?.tier ?? DEMAND_TAG_DEFAULT_TIER_VALUES[3].value));
        // from info for existing tag, from pageConfig(queries) for new tag
      }

      if (pageConfig?.isCreatingNew && pageConfig.demandAccount?.publisherDemand) {
        setSettings.supplyChainOverride = DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled;
      }

      if (info) {
        setSettings.name = pageConfig?.isDuplicate ? `Copy_of_${info.name}` : info.name;
        setSettings.source = info?.source;
        setSettings.platformId = info?.platformId || '';
        setSettings.status = pageConfig?.isDuplicate ? DEMAND_TAG_STATUS.enabled : info.status;
        setSettings.uid = info.id;
        setSettings.adServer = info.adServer;
        setSettings.url = info.adServer?.url ?? '';
        setSettings.format = info.format ?? DEMAND_TAG_FORMAT.video;
        setSettings.priority = info.priority;
        setSettings.videoId = info.videoId ?? '';
        setSettings.clickThroughUrl = info.clickThroughUrl ?? '';

        if (info.adServer?.name) {
          setSettings.adServerType = 'list';
        }

        if (info.labels?.length) {
          setSettings.labels = info.labels;
        }

        setSettings.timeout = info.timeout;

        if (info.eventPixels?.length) {
          setSettings.eventPixelsList = info.eventPixels.map((pixel, index) => ({
            id: index,
            url: pixel.url,
            event: pixel.name,
            type: pixel.type,
          }));
        }

        setSettings.type = info.type;

        if (info.platform) {
          if (info.platform.params?.length) {
            const params = info.platform.params.reduce(
              (acc, curr) => ({
                ...acc,
                [curr.name]: curr.value,
              }),
              {},
            );
            setSettings.platform = {
              name: info.platform.connectorName,
              connectorId: info.platform.connectorId,
              code: info.platform.code,
              ...params,
            };
          } else {
            setSettings.platform = {
              name: info.platform.connectorName,
              connectorId: info.platform.connectorId,
              code: info.platform.code,
            };
          }

          if (info.platform.bidMapping?.fileName?.length) {
            setSettings.bidMappingFileName = info.platform.bidMapping.fileName;
            setSettings.bidMappingFileData = info.platform.bidMapping.data;
          }

          if (info.platform.supplyChain !== null) {
            setSettings.supplyChainOverride = DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.enabled;
            if (info.platform.supplyChain?.length > 0) {
              setSettings.supplyChainValue = DEMAND_TAG_SUPPLY_CHAIN_VALUE.custom;
              setSettings.supplyChainNode = info.platform.supplyChain;
            } else {
              setSettings.supplyChainValue = DEMAND_TAG_SUPPLY_CHAIN_VALUE.blank;
            }
          }

          if (info.platform.maxFloor) {
            setSettings.maxFloor = info.platform.maxFloor;
          }
        }

        if (info.floorPrice?.override) {
          setSettings.floorPrice = {
            override: FLOOR_PRICE.override,
            floor: info.floorPrice?.floor,
            viewableFloor: info.floorPrice?.viewableFloor,
          };
        }

        if (info.adjustFloor !== null && info.adjustFloor !== undefined) {
          setSettings.adjustFloor = info.adjustFloor;
        }
        if (info.flightsDates) {
          setSettings.flightsDates = info.flightsDates;
        }
      }

      return concat(of(setSettingsTabAction(setSettings)));
    }),
  );
