/**
 * Custom Validators
 */

/**
 * Validate email format
 */
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

/**
 * Validate phone number
 */
const isValidPhone = (phone) => {
  const phoneRegex =
    /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/;
  return phoneRegex.test(phone);
};

/**
 * Validate password strength
 */
const isStrongPassword = (password) => {
  // At least 8 characters, 1 uppercase, 1 lowercase, 1 number
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{8,}$/;
  return passwordRegex.test(password);
};

/**
 * Validate date format (YYYY-MM-DD)
 */
const isValidDate = (dateString) => {
  const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
  if (!dateRegex.test(dateString)) return false;

  const date = new Date(dateString);
  return date instanceof Date && !isNaN(date);
};

/**
 * Validate NIC format (Sri Lanka format example)
 */
const isValidNIC = (nic) => {
  // Old format: 9 digits + V/X or New format: 12 digits
  const nicRegex = /^([0-9]{9}[vVxX]|[0-9]{12})$/;
  return nicRegex.test(nic);
};

/**
 * Sanitize string input
 */
const sanitizeString = (str) => {
  if (typeof str !== "string") return "";
  return str.trim().replace(/[<>]/g, "");
};

/**
 * Validate required fields
 */
const validateRequired = (obj, requiredFields) => {
  const missing = [];

  for (const field of requiredFields) {
    if (
      !obj[field] ||
      (typeof obj[field] === "string" && obj[field].trim() === "")
    ) {
      missing.push(field);
    }
  }

  return {
    isValid: missing.length === 0,
    missing,
  };
};

module.exports = {
  isValidEmail,
  isValidPhone,
  isStrongPassword,
  isValidDate,
  isValidNIC,
  sanitizeString,
  validateRequired,
};
