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

import { PCN_GET_MARKETPLACE_DASHBOARD } from '@/modules/@common/acl/constants';

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

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

      const advertiserSettings = selectors.advertiserSettingsSelector(state);

      const { name, demandAccountId, frequencyCapAdjustment, frequencyCapAdjustmentThreshold } = advertiserSettings;

      const userPermissions = getUserPermissionsSelector(state);
      const isAdminMP = hasPermission(PCN_GET_MARKETPLACE_DASHBOARD, userPermissions);

      if (!isAdminMP) {
        if (!name?.length) {
          return concat(
            of(
              setAdvertiserSettingsTabAction({
                errors: {
                  name: 'Field cannot be empty',
                },
              }),
            ),
          );
        }

        if (!demandAccountId) {
          return concat(
            of(
              setAdvertiserSettingsTabAction({
                errors: {
                  demandAccountId: 'Field cannot be empty',
                },
              }),
            ),
          );
        }
      }

      if (frequencyCapAdjustment && frequencyCapAdjustmentThreshold?.length === 0) {
        return concat(
          of(
            setAdvertiserSettingsTabAction({
              errors: {
                frequencyCapAdjustmentThreshold: 'Field cannot be empty',
              },
            }),
          ),
        );
      }

      return concat(of(action.payload()));
    }),
  );
