import { Address, MapAddresse } from "@/shared/types/infrastructure";

export const getFormatedAddress = (mapAddress: MapAddresse): Address => {
    const street = extractStreetAddressPart(mapAddress);
    const postalCode = mapAddress.postalCode;
    const city = mapAddress.city;
    const country = mapAddress.country;
    const lat = mapAddress.lat;
    const lng = mapAddress.lng;

    return {
        id: 0,
        createdAt: '',
        updatedAt: '',
        street,
        zipCode: postalCode,
        city,
        country,
        latitude: lat,
        longitude: lng,
    };
};

function extractStreetAddressPart(mapAddress: MapAddresse): string {
    const { address, city, postalCode, country } = mapAddress;
    const regexParts = [city, postalCode, country]
        .filter(Boolean)
        .map(str => escapeRegExp(str.toLowerCase()));
    if (!address || regexParts.length === 0) {
        return address;
    }
    const parts = address.split(',').map(p => p.trim());
    const resultParts: string[] = [];
    let hasSeenStreetPart = false;
    for (const part of parts) {
        const lowerPart = part.toLowerCase();
        const matchesBlacklist = regexParts.some(r => lowerPart.includes(r));

        if (!hasSeenStreetPart && !matchesBlacklist) {
            hasSeenStreetPart = true;
            resultParts.push(part);
        } else if (hasSeenStreetPart && !matchesBlacklist) {
            resultParts.push(part);
        }
    }
    return resultParts.join(', ').trim();
}

function escapeRegExp(str: string): string {
    return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}