import { TAB_ADVANCED, TAB_BASIC_DETAILS, TAB_CONFIGURATION, TAB_CUSTOM } from '../constants';

import { isValidUrl } from '@/modules/@common/helpers/string';

export const validationScheme = [
  {
    fieldName: 'hub',
    tabId: TAB_BASIC_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Hub is required';
      }

      return '';
    },
  },
  {
    fieldName: 'title',
    tabId: TAB_BASIC_DETAILS,
    validation: (title) => {
      const value = title?.trim();

      if (!value) {
        return 'Field cannot be empty';
      }
      if (value.length < 2) {
        return 'Field cannot be less then 2 symbols';
      }

      return '';
    },
  },
  {
    fieldName: 'source',
    tabId: TAB_BASIC_DETAILS,
    validation: (value) => {
      if (!value?.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'domain',
    tabId: TAB_BASIC_DETAILS,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'sitemap',
    tabId: TAB_BASIC_DETAILS,
    validation: (value) => {
      if (typeof value === 'boolean' && value === true) {
        return '';
      }

      if (!value) {
        return 'Field cannot be empty';
      }
      if (!isValidUrl(value)) {
        return 'Wrong link format';
      }

      return '';
    },
  },
  {
    fieldName: 'dsTags',
    tabId: TAB_ADVANCED,
    validation: (value) => {
      if (!value.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'adHubId',
    tabId: TAB_ADVANCED,
    validation: (value) => {
      if (!value.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'adWidgetId',
    tabId: TAB_ADVANCED,
    validation: (value) => {
      if (!value.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
  {
    fieldName: 'widgetOrigin',
    tabId: TAB_CUSTOM,
    validation: (value) => {
      if (value && !isValidUrl(value)) {
        return 'Wrong URL format';
      }

      return '';
    },
  },
  {
    fieldName: 'js',
    tabId: TAB_CUSTOM,
    validation: (value) => {
      try {
        // eslint-disable-next-line no-new-func
        new Function(value)();
      } catch (e) {
        return e.message;
      }

      return '';
    },
  },
  {
    fieldName: 'configuration',
    tabId: TAB_CONFIGURATION,
    validation: (value) => {
      try {
        if (value) {
          const parsed = JSON.parse(value);
          if (typeof parsed !== 'object' || parsed === null) {
            throw new Error();
          }
        }

        return '';
      } catch {
        return 'Invalid JSON format';
      }
    },
  },
];
