// Common validation patterns used across microfrontends

export const ValidationPatterns = {
  email: /^\S+@\S+\.\S+$/,
  url: /^https?:\/\/.+/,
  duration: /^\d+[smhd]$/,  // e.g., "30s", "5m", "2h", "1d"
  token: /^[a-zA-Z0-9_-]+$/,
  appId: /^[a-zA-Z0-9-_]+$/,
  uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,
};

export const ValidationMessages = {
  required: (fieldName: string) => `${fieldName} is required`,
  email: 'Please enter a valid email address',
  url: 'Please enter a valid URL (http:// or https://)',
  duration: 'Duration must be in format like 30s, 5m, 2h, 1d',
  minLength: (fieldName: string, minLength: number) => 
    `${fieldName} must be at least ${minLength} characters`,
  maxLength: (fieldName: string, maxLength: number) => 
    `${fieldName} must be no more than ${maxLength} characters`,
  pattern: (fieldName: string) => `${fieldName} format is invalid`,
  token: 'Token can only contain letters, numbers, underscores and hyphens',
  appId: 'App ID can only contain letters, numbers, hyphens and underscores',
  uuid: 'Please enter a valid UUID',
  positiveNumber: 'Must be a positive number',
  range: (fieldName: string, min: number, max: number) => 
    `${fieldName} must be between ${min} and ${max}`,
};

// Common validation functions
export const validateRequired = (value: any): string | null => {
  if (value === null || value === undefined || value === '' || 
      (Array.isArray(value) && value.length === 0)) {
    return 'This field is required';
  }
  return null;
};

export const validateEmail = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.email.test(value) ? null : ValidationMessages.email;
};

export const validateUrl = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.url.test(value) ? null : ValidationMessages.url;
};

export const validateDuration = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.duration.test(value) ? null : ValidationMessages.duration;
};

export const validateMinLength = (value: string, minLength: number, fieldName = 'Field'): string | null => {
  if (!value) return null;
  return value.length >= minLength ? null : ValidationMessages.minLength(fieldName, minLength);
};

export const validateMaxLength = (value: string, maxLength: number, fieldName = 'Field'): string | null => {
  if (!value) return null;
  return value.length <= maxLength ? null : ValidationMessages.maxLength(fieldName, maxLength);
};

export const validatePattern = (value: string, pattern: RegExp, fieldName = 'Field'): string | null => {
  if (!value) return null;
  return pattern.test(value) ? null : ValidationMessages.pattern(fieldName);
};

export const validateRange = (value: number, min: number, max: number, fieldName = 'Field'): string | null => {
  if (value == null) return null;
  if (value < min || value > max) {
    return ValidationMessages.range(fieldName, min, max);
  }
  return null;
};

export const validateAppId = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.appId.test(value) ? null : ValidationMessages.appId;
};

export const validateToken = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.token.test(value) ? null : ValidationMessages.token;
};

export const validateUuid = (value: string): string | null => {
  if (!value) return null;
  return ValidationPatterns.uuid.test(value) ? null : ValidationMessages.uuid;
};

export const validateJsonString = (value: string): string | null => {
  if (!value || value.trim() === '') return null;
  
  try {
    JSON.parse(value);
    return null;
  } catch (error) {
    return 'Invalid JSON format';
  }
};

// Utility function to parse duration strings to seconds (common across KMS and FaaS)
export const parseDuration = (duration: string): number => {
  const match = duration.match(/^(\d+)([smhd]?)$/);
  if (!match) return 86400; // Default to 24h in seconds
  
  const value = parseInt(match[1]);
  const unit = match[2] || 'h';
  
  switch (unit) {
    case 's': return value; // seconds
    case 'm': return value * 60; // minutes to seconds
    case 'h': return value * 3600; // hours to seconds  
    case 'd': return value * 86400; // days to seconds
    default: return value * 3600; // default to hours
  }
};

// Utility function to format duration from seconds to human readable
export const formatDuration = (seconds: number): string => {
  if (seconds < 60) return `${seconds}s`;
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
  return `${Math.floor(seconds / 86400)}d`;
};

// Combine multiple validators
export const combineValidators = (...validators: Array<(value: any) => string | null>) => {
  return (value: any): string | null => {
    for (const validator of validators) {
      const error = validator(value);
      if (error) return error;
    }
    return null;
  };
};