WITH mismatched AS (
    SELECT
        ir.id AS range_id,
        ir.service_address
    FROM internet_connections_ip_ranges ir
    JOIN internet_connections_connections current_conn
      ON current_conn.id = ir.connection_id
    WHERE ir.deleted_at IS NULL
      AND current_conn.deleted_at IS NULL
      AND current_conn.allocation_model <> 'shared'
      AND ir.service_address IS NOT NULL
      AND regexp_replace(upper(coalesce(ir.service_address, '')), '[^A-Z0-9]', '', 'g')
          <> regexp_replace(upper(coalesce(current_conn.address, '')), '[^A-Z0-9]', '', 'g')
),
candidate_matches AS (
    SELECT
        m.range_id,
        candidate.id AS target_connection_id,
        COUNT(*) OVER (PARTITION BY m.range_id) AS candidate_count
    FROM mismatched m
    JOIN internet_connections_connections candidate
      ON candidate.deleted_at IS NULL
     AND regexp_replace(upper(coalesce(candidate.address, '')), '[^A-Z0-9]', '', 'g')
         = regexp_replace(upper(coalesce(m.service_address, '')), '[^A-Z0-9]', '', 'g')
),
unique_targets AS (
    SELECT range_id, target_connection_id
    FROM candidate_matches
    WHERE candidate_count = 1
)
UPDATE internet_connections_ip_ranges ir
SET connection_id = ut.target_connection_id,
    updated_at = CURRENT_TIMESTAMP
FROM unique_targets ut
WHERE ir.id = ut.range_id;
