import { TAB_GENERAL } from '../constants';
import { PROVIDER_VALUE_GOOGLE } from '@/modules/sso/List/constants';

// moved from original sso domain validation
const domainRegExp = /^(?!:\/\/)([a-zA-Z0-9-]{1,63}\.){1,4}[a-zA-Z]{2,11}$/;
const urlRegExp = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/;

export const validationScheme = [
  {
    fieldName: 'displayName',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      if (value.length < 2) {
        return 'Minimum 2 letters';
      }

      return '';
    },
  },
  {
    fieldName: 'domains',
    tabId: TAB_GENERAL,
    dynamic: true,
    validation: (domains, fields) => {
      if (fields.allDomains) {
        return '';
      }
      return domains.reduce((acc, value, index) => {
        const trimmedValue = value?.trim();
        let errorMessage = '';

        if (!trimmedValue) {
          errorMessage = 'Field cannot be empty';
        } else if (!domainRegExp.test(trimmedValue)) {
          errorMessage = 'Invalid domain';
        }

        acc[index] = errorMessage;

        return acc;
      }, {});
    },
  },
  {
    fieldName: 'metadataURL',
    tabId: TAB_GENERAL,
    validation: (value, fields) => {
      if (fields.provider === PROVIDER_VALUE_GOOGLE) {
        return '';
      }
      if (!value) {
        return 'Field cannot be empty';
      }

      if (!urlRegExp.test(value)) {
        return 'Field must be a valid URL';
      }

      return '';
    },
  },
  {
    fieldName: 'ssoDefaultHubs',
    tabId: TAB_GENERAL,
    validation: (value, fields) => {
      if (fields.onlyExisting) {
        return '';
      }
      if (!value.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
];

export const validationAttributesScheme = [
  {
    fieldName: 'attributeName',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value) {
        return 'Field cannot be empty';
      }

      if (value.length < 2) {
        return 'Minimum 2 letters';
      }

      return '';
    },
  },
  {
    fieldName: 'attributesKeyValues',
    tabId: TAB_GENERAL,
    dynamic: true,
    validation: (attributesKeyValues) =>
      attributesKeyValues.reduce((acc, [key, value], index) => {
        acc[index] = {
          key: !urlRegExp.test(key) ? 'Invalid key pattern' : '',
          value: !value ? 'Field cannot be empty' : '',
        };
        return acc;
      }, {}),
  },
  {
    fieldName: 'attributeHubs',
    tabId: TAB_GENERAL,
    validation: (value) => {
      if (!value.length) {
        return 'Field cannot be empty';
      }

      return '';
    },
  },
];
