/**
 * Centralized Form Validation Rules and Regex Patterns
 * Ensures uniform, strict validation across all CRM forms.
 */

import type { Rule } from 'antd/es/form';

/**
 * Standard Phone number pattern:
 * - Optional leading + (e.g. +91, +1)
 * - Leading digit (cannot start with space or special char)
 * - Digits, spaces, hyphens, parentheses only
 * - Length between 7 and 20 characters
 * - No letters allowed
 */
export const PHONE_PATTERN = /^\+?[0-9][0-9\s()-]{5,19}$/;
export const PHONE_MESSAGE = 'Enter a valid phone number (digits, spaces, +, - or brackets only)';

/**
 * Website URL pattern:
 * Allows http://, https://, or bare domain like company.com, tech.co.in
 */
export const WEBSITE_PATTERN = /^(https?:\/\/)?([a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(\/[^\s]*)?$/i;
export const WEBSITE_MESSAGE = 'Enter a valid website URL (e.g. https://example.com or example.com)';

/**
 * Ant Design Form rule for Phone fields:
 * - Skips empty optional values
 * - Rejects any alphabetical characters or symbols outside + - ( )
 * - Validates digit count (must contain between 7 and 15 actual digits)
 */
export const phoneValidationRule: Rule = {
  validator(_: unknown, value?: string | null) {
    if (!value || !value.trim()) {
      return Promise.resolve();
    }
    const clean = value.trim();
    if (!PHONE_PATTERN.test(clean)) {
      return Promise.reject(new Error(PHONE_MESSAGE));
    }
    const digitsOnly = clean.replace(/\D/g, '');
    if (digitsOnly.length < 7 || digitsOnly.length > 15) {
      return Promise.reject(new Error('Phone number must contain between 7 and 15 digits'));
    }
    return Promise.resolve();
  },
};

/**
 * Ant Design Form rule for Website fields:
 * - Skips empty optional values
 * - Validates domain and format
 */
export const websiteValidationRule: Rule = {
  validator(_: unknown, value?: string | null) {
    if (!value || !value.trim()) {
      return Promise.resolve();
    }
    const clean = value.trim();
    if (!WEBSITE_PATTERN.test(clean)) {
      return Promise.reject(new Error(WEBSITE_MESSAGE));
    }
    return Promise.resolve();
  },
};

/**
 * Ant Design Form rule for Email fields.
 */
export const emailValidationRule = (required = false): Rule[] => [...(required ? [{ required: true, whitespace: true, message: 'Email address is required' }] : []), { type: 'email' as const, message: 'Enter a valid email address (e.g. name@company.com)' }, { max: 255, message: 'Email cannot exceed 255 characters' }];

/**
 * Helper to ensure a required text field is non-empty and not just spaces.
 */
export const requiredTextRule = (fieldName: string, maxLen = 255): Rule[] => [
  { required: true, whitespace: true, message: `Enter the ${fieldName.toLowerCase()}` },
  { max: maxLen, message: `${fieldName} cannot exceed ${maxLen} characters` },
];

/**
 * Helper for non-negative number inputs.
 */
export const nonNegativeNumberRule = (fieldName: string, max = 100000000000): Rule => ({
  validator(_: unknown, value?: number | null) {
    if (value === undefined || value === null) return Promise.resolve();
    if (Number.isNaN(Number(value)) || Number(value) < 0) {
      return Promise.reject(new Error(`${fieldName} cannot be negative`));
    }
    if (Number(value) > max) {
      return Promise.reject(new Error(`${fieldName} exceeds maximum allowable limit`));
    }
    return Promise.resolve();
  },
});
