import { STATE_ID_TO_ABBR } from '../constants/states';

export const formatZip = (zip: string | number): string => {
    return String(zip || '').trim().padStart(5, '0');
};

/**
 * Formats an address string with street, town, state, and zip.
 * Handles missing or invalid state IDs gracefully.
 * 
 * @param address Street address (e.g. "123 Main St")
 * @param town Town name (e.g. "Springfield")
 * @param stateId State ID (integer)
 * @param zip Zip code
 * @param includeUsa Whether to append ", USA" (default false)
 * @returns Formatted address string
 */
export const formatAddress = (
    address: string,
    town: string,
    stateId: number | string,
    zip: string | number
): string => {
    const cleanAddress = (address || '').trim();
    const cleanTown = (town || '').trim();
    const cleanZip = formatZip(zip);

    const parsedStateId = typeof stateId === 'string' ? parseInt(stateId, 10) : stateId;
    const stateAbbr = STATE_ID_TO_ABBR[parsedStateId] || 'MA'; // Default to MA if not found

    let formatted = cleanAddress;

    if (cleanTown) {
        formatted += formatted ? `, ${cleanTown}` : cleanTown;
    }

    if (stateAbbr) {
        formatted += formatted ? `, ${stateAbbr}` : stateAbbr;
    }

    if (cleanZip) {
        formatted += formatted ? ` ${cleanZip}` : cleanZip;
    }

    return formatted;
};

/**
 * Generates a Google Maps link for the given address components.
 * 
 * @param address Street address
 * @param town Town name
 * @param stateId State ID
 * @param zip Zip code
 * @returns Google Maps URL
 */
export const getGoogleMapsLink = (
    address: string,
    town: string,
    stateId: number | string,
    zip: string | number
): string => {
    const fullAddress = formatAddress(address, town, stateId, zip);
    return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(fullAddress)}`;
};
