/**
 * Extracts the first numeric sequence from an address string.
 * @param {string} address - The address string.
 * @returns {number} The extracted number, or 0 if none found.
 */
export function extractAddressNumber(address) {
  if (!address || typeof address !== 'string') return 0;
  
  // Match the first sequence of digits in the string
  const match = address.match(/(\d+)/);
  
  if (match && match[0]) {
    // Parse integer base 10
    return parseInt(match[0], 10);
  }
  
  // If no number found, treat as 0 (will appear at top of sort usually, or handle as needed)
  return 0;
}

/**
 * Sorts an array of owner objects by their property address number in ascending numerical order.
 * Handles edge cases like null addresses or addresses without numbers.
 * Provides a secondary alphanumeric sort on the full address for stability.
 * 
 * @param {Array} owners - Array of owner objects.
 * @returns {Array} Sorted array of owners.
 */
export function sortOwnersByAddressNumber(owners) {
  if (!Array.isArray(owners)) return [];
  
  return [...owners].sort((a, b) => {
    const addressA = a.property_address || '';
    const addressB = b.property_address || '';
    
    const numA = extractAddressNumber(addressA);
    const numB = extractAddressNumber(addressB);
    
    // Primary sort: Numerical by address number
    if (numA !== numB) {
      return numA - numB;
    }
    
    // Secondary sort: Alphabetical by full address string for stability if numbers match (or are both 0)
    // using numeric: true allows "Unit 2" to sort before "Unit 10" if extraction failed to get distinct primary numbers
    return addressA.localeCompare(addressB, undefined, { numeric: true, sensitivity: 'base' });
  });
}