WITH normalized_extraction_addresses AS (
    SELECT
        regexp_replace(UPPER(COALESCE(provider_reference, circuit_id, '')), '[^A-Z0-9]', '', 'g') AS ref_norm,
        NULLIF(BTRIM(service_address), '') AS service_address
    FROM extraction_lines
    WHERE NULLIF(BTRIM(service_address), '') IS NOT NULL
),
unique_addresses AS (
    SELECT
        ref_norm,
        MIN(service_address) AS service_address
    FROM normalized_extraction_addresses
    GROUP BY ref_norm
    HAVING COUNT(DISTINCT service_address) = 1
)
UPDATE internet_connections_connections c
SET address = u.service_address,
    updated_at = CURRENT_TIMESTAMP,
    notes = CONCAT(
        COALESCE(c.notes, ''),
        CASE WHEN COALESCE(c.notes, '') = '' THEN '' ELSE E'\n' END,
        'Adresse backfill fra extraction-data.'
    )
FROM unique_addresses u
WHERE c.deleted_at IS NULL
  AND (c.address IS NULL OR BTRIM(c.address) = '')
  AND regexp_replace(UPPER(COALESCE(c.circuit_number, '')), '[^A-Z0-9]', '', 'g') = u.ref_norm;
