import {
  DEMAND_ACCOUNT_PAGE,
  DEMAND_ADVERTISER_PAGE,
  DEMAND_TAG_PAGE,
  SUPPLY_ACCOUNT_PAGE,
  SUPPLY_SITE_PAGE,
  SUPPLY_TAG_PAGE,
} from '../constants';

export const addParamsToFilters = (params, newParams) => {
  if (Array.isArray(params.filters)) {
    return {
      ...params,
      filters: params.filters.map((filter) => ({
        ...filter,
        ...newParams,
      })),
    };
  }

  return {
    ...params,
    filters: {
      ...params.filters,
      ...newParams,
    },
  };
};

export const addPageParams = (mainParams, pageConfig, isAdminMP = true, isDataTableRequest) => {
  if (pageConfig.type === SUPPLY_ACCOUNT_PAGE) {
    return addParamsToFilters(mainParams, { accountIds: [{ value: pageConfig.id }] });
  }

  if (pageConfig.type === SUPPLY_SITE_PAGE) {
    return addParamsToFilters(mainParams, { siteId: pageConfig.id });
  }

  if (pageConfig.type === SUPPLY_TAG_PAGE) {
    if (!isAdminMP && isDataTableRequest) {
      return {
        ...addParamsToFilters(mainParams, { ssSupplyId: pageConfig.id }),
        advertiserTargeting: true,
      };
    }

    return {
      ...addParamsToFilters(mainParams, { supplyId: { value: pageConfig.id } }),
      advertiserTargeting: true,
    };
  }

  if (pageConfig.type === DEMAND_ACCOUNT_PAGE) {
    return addParamsToFilters(mainParams, { daccountIds: [{ value: pageConfig.id }] });
  }

  if (pageConfig.type === DEMAND_ADVERTISER_PAGE) {
    return {
      ...addParamsToFilters(mainParams, { advertiserId: pageConfig.id }),
      advertiserTargeting: true,
    };
  }

  if (pageConfig.type === DEMAND_TAG_PAGE) {
    return addParamsToFilters(mainParams, { demandId: { value: pageConfig.id } });
  }

  return mainParams;
};

export default addParamsToFilters;
