/**
 * Contact Form Validation Module
 *
 * Centralized validation logic for contact form submissions.
 * All validation rules are defined here for easy maintenance and testing.
 *
 * @module lib/validators/contact.validator
 */

import validator from 'validator';
import type {
  ContactFormData,
  ContactValidationError,
  ContactTopic,
} from '../types/contact.types';

/**
 * Configuration for contact form validation rules
 * Modify these constants to change validation behavior
 */
export const CONTACT_VALIDATION_RULES = {
  /** Minimum name length */
  NAME_MIN_LENGTH: 2,

  /** Maximum name length */
  NAME_MAX_LENGTH: 100,

  /** Minimum message length */
  MESSAGE_MIN_LENGTH: 10,

  /** Maximum message length */
  MESSAGE_MAX_LENGTH: 10000,

  /** Maximum company name length */
  COMPANY_MAX_LENGTH: 255,

  /** Allowed languages */
  ALLOWED_LANGUAGES: ['ar', 'en'] as const,

  /** Allowed topics (must match form options) */
  ALLOWED_TOPICS: [
    'sales',
    'support',
    'billing',
    'partnerships',
    'press',
    'careers',
    'security',
    'demo',
    'other',
  ] as const,
} as const;

/**
 * Validate contact form data
 *
 * Performs comprehensive validation of all contact form fields.
 * Returns an array of validation errors (empty if valid).
 *
 * @param data - Partial contact form data to validate
 * @returns Array of validation errors (empty if valid)
 *
 * @example
 * ```typescript
 * const errors = validateContactForm(formData);
 * if (errors.length > 0) {
 *   return Response.json({ errors }, { status: 400 });
 * }
 * ```
 */
export function validateContactForm(
  data: Partial<ContactFormData>
): ContactValidationError[] {
  const errors: ContactValidationError[] = [];

  // Validate name
  if (!data.name || data.name.trim().length === 0) {
    errors.push({
      field: 'name',
      message: 'Name is required',
      code: 'NAME_REQUIRED',
    });
  } else if (data.name.trim().length < CONTACT_VALIDATION_RULES.NAME_MIN_LENGTH) {
    errors.push({
      field: 'name',
      message: `Name must be at least ${CONTACT_VALIDATION_RULES.NAME_MIN_LENGTH} characters`,
      code: 'NAME_TOO_SHORT',
    });
  } else if (data.name.length > CONTACT_VALIDATION_RULES.NAME_MAX_LENGTH) {
    errors.push({
      field: 'name',
      message: `Name must be less than ${CONTACT_VALIDATION_RULES.NAME_MAX_LENGTH} characters`,
      code: 'NAME_TOO_LONG',
    });
  }

  // Validate email
  if (!data.email) {
    errors.push({
      field: 'email',
      message: 'Email is required',
      code: 'EMAIL_REQUIRED',
    });
  } else if (!validator.isEmail(data.email)) {
    errors.push({
      field: 'email',
      message: 'Invalid email address',
      code: 'EMAIL_INVALID',
    });
  }

  // Validate phone (optional but must be valid if provided)
  if (data.phone && data.phone.trim().length > 0) {
    if (!validator.isMobilePhone(data.phone, 'any', { strictMode: false })) {
      errors.push({
        field: 'phone',
        message: 'Invalid phone number',
        code: 'PHONE_INVALID',
      });
    }
  }

  // Validate company (optional but check length if provided)
  if (data.company && data.company.length > CONTACT_VALIDATION_RULES.COMPANY_MAX_LENGTH) {
    errors.push({
      field: 'company',
      message: `Company name must be less than ${CONTACT_VALIDATION_RULES.COMPANY_MAX_LENGTH} characters`,
      code: 'COMPANY_TOO_LONG',
    });
  }

  // Validate topic
  if (!data.topic) {
    errors.push({
      field: 'topic',
      message: 'Inquiry type is required',
      code: 'TOPIC_REQUIRED',
    });
  } else if (!CONTACT_VALIDATION_RULES.ALLOWED_TOPICS.includes(data.topic as any)) {
    errors.push({
      field: 'topic',
      message: 'Invalid inquiry type',
      code: 'TOPIC_INVALID',
    });
  }

  // Validate message
  if (!data.message || data.message.trim().length === 0) {
    errors.push({
      field: 'message',
      message: 'Message is required',
      code: 'MESSAGE_REQUIRED',
    });
  } else if (data.message.trim().length < CONTACT_VALIDATION_RULES.MESSAGE_MIN_LENGTH) {
    errors.push({
      field: 'message',
      message: `Message must be at least ${CONTACT_VALIDATION_RULES.MESSAGE_MIN_LENGTH} characters`,
      code: 'MESSAGE_TOO_SHORT',
    });
  } else if (data.message.trim().length > CONTACT_VALIDATION_RULES.MESSAGE_MAX_LENGTH) {
    errors.push({
      field: 'message',
      message: `Message must be less than ${CONTACT_VALIDATION_RULES.MESSAGE_MAX_LENGTH} characters`,
      code: 'MESSAGE_TOO_LONG',
    });
  }

  // Validate preferred language
  if (!data.preferredLanguage) {
    errors.push({
      field: 'preferredLanguage',
      message: 'Preferred language is required',
      code: 'LANGUAGE_REQUIRED',
    });
  } else if (!CONTACT_VALIDATION_RULES.ALLOWED_LANGUAGES.includes(data.preferredLanguage)) {
    errors.push({
      field: 'preferredLanguage',
      message: 'Invalid language selection',
      code: 'LANGUAGE_INVALID',
    });
  }

  // Validate consent
  if (!data.consentGiven) {
    errors.push({
      field: 'consent',
      message: 'You must agree to the privacy policy and terms',
      code: 'CONSENT_REQUIRED',
    });
  }

  return errors;
}

/**
 * Quick validation check - returns true if data is valid
 *
 * @param data - Contact form data to validate
 * @returns True if valid, false otherwise
 *
 * @example
 * ```typescript
 * if (!isContactDataValid(formData)) {
 *   throw new Error('Invalid form data');
 * }
 * ```
 */
export function isContactDataValid(data: Partial<ContactFormData>): boolean {
  return validateContactForm(data).length === 0;
}

/**
 * Validate a single field
 *
 * Useful for real-time validation in the frontend
 *
 * @param field - Field name to validate
 * @param value - Value to validate
 * @param data - Full form data (for context-dependent validation)
 * @returns Validation error or null if valid
 *
 * @example
 * ```typescript
 * const error = validateField('email', 'invalid', formData);
 * if (error) {
 *   showError(error.message);
 * }
 * ```
 */
export function validateField(
  field: keyof ContactFormData,
  value: any,
  data?: Partial<ContactFormData>
): ContactValidationError | null {
  const errors = validateContactForm({ ...data, [field]: value });
  return errors.find(e => e.field === field) || null;
}

/**
 * Check if a topic is valid
 *
 * @param topic - Topic to check
 * @returns True if topic is in allowed list
 */
export function isValidTopic(topic: string): topic is ContactTopic {
  return CONTACT_VALIDATION_RULES.ALLOWED_TOPICS.includes(topic as any);
}

/**
 * Check if a language is valid
 *
 * @param lang - Language code to check
 * @returns True if language is supported
 */
export function isValidLanguage(lang: string): lang is 'ar' | 'en' {
  return CONTACT_VALIDATION_RULES.ALLOWED_LANGUAGES.includes(lang as any);
}

/**
 * Get user-friendly error message
 *
 * Converts validation errors into user-friendly messages
 * with language support
 *
 * @param errors - Array of validation errors
 * @param language - Language for error messages
 * @returns Formatted error message
 */
export function getErrorMessage(
  errors: ContactValidationError[],
  language: 'ar' | 'en' = 'en'
): string {
  if (errors.length === 0) return '';

  const messages = errors.map(e => e.message);

  if (language === 'ar') {
    // Arabic error messages
    return `يرجى تصحيح الأخطاء التالية: ${messages.join('، ')}`;
  }

  // English error messages
  return `Please correct the following errors: ${messages.join(', ')}`;
}
