import { splitMailingAddressLines } from './ownerAddressUtils';

/**
 * Formats a mailing address for letters/notices.
 * Ensures the format: Owner Name(s)\nStreet Address\nCity, State Zip
 * 
 * If mailing_address is missing, falls back to property_address.
 * Single-line addresses are intelligently split into street + city/state/zip.
 * 
 * @param owner - Owner object with address fields
 * @param ownerNames - Pre-formatted owner name string (e.g. "John & Jane Doe")
 * @returns Object with formatted address lines array and full address string
 */
export function formatMailingAddress(
  owner: {
    mailing_address?: string | null;
    property_address?: string | null;
    street_address?: string | null;
    first_name?: string | null;
    last_name?: string | null;
    owner_name?: string | null;
  },
  ownerNames?: string
): { lines: string[]; full: string; name: string } {
  const name = ownerNames
    || owner.owner_name
    || `${owner.first_name || ''} ${owner.last_name || ''}`.trim()
    || 'Owner';

  // Use mailing_address first, fall back to property_address
  const rawAddress = owner.mailing_address || owner.property_address || owner.street_address || '';

  // Use smart splitting that handles single-line "Street, City, ST 12345" formats
  const addressLines = splitMailingAddressLines(rawAddress);

  // Full formatted address: Name on first line, then address lines
  const allLines = [name, ...addressLines];
  const full = allLines.join('\n');

  return { lines: addressLines, full, name };
}

/**
 * Splits a formatted address into the standard 4-line form fields:
 * Line 1: Owner name(s)
 * Line 2: Street address
 * Line 3: City, State Zip (or second address line)
 * Line 4: Additional line (if any)
 */
export function getAddressFormLines(
  owner: {
    mailing_address?: string | null;
    property_address?: string | null;
    street_address?: string | null;
    first_name?: string | null;
    last_name?: string | null;
    owner_name?: string | null;
  },
  ownerNames?: string
): { line1: string; line2: string; line3: string; line4: string } {
  const { lines, name } = formatMailingAddress(owner, ownerNames);

  return {
    line1: name,
    line2: lines[0] || '',
    line3: lines[1] || '',
    line4: lines[2] || '',
  };
}
