WITH bad_connections AS (
    SELECT id
    FROM internet_connections_connections
    WHERE deleted_at IS NULL
      AND provider ILIKE 'GlobalConnect%'
      AND (address IS NULL OR BTRIM(address) = '')
)
UPDATE internet_connections_ip_addresses
SET deleted_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP,
    comment = CONCAT(
        COALESCE(comment, ''),
        CASE WHEN COALESCE(comment, '') = '' THEN '' ELSE E'\n' END,
        'Skjult sammen med fejlimporteret forbindelse uden adresse.'
    )
WHERE deleted_at IS NULL
  AND range_id IN (
      SELECT id
      FROM internet_connections_ip_ranges
      WHERE connection_id IN (SELECT id FROM bad_connections)
        AND deleted_at IS NULL
  );

WITH bad_connections AS (
    SELECT id
    FROM internet_connections_connections
    WHERE deleted_at IS NULL
      AND provider ILIKE 'GlobalConnect%'
      AND (address IS NULL OR BTRIM(address) = '')
)
UPDATE internet_connections_ip_ranges
SET deleted_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP,
    description = CONCAT(
        COALESCE(description, ''),
        CASE WHEN COALESCE(description, '') = '' THEN '' ELSE E'\n' END,
        'Skjult sammen med fejlimporteret forbindelse uden adresse.'
    )
WHERE deleted_at IS NULL
  AND connection_id IN (SELECT id FROM bad_connections);

UPDATE internet_connections_connections
SET deleted_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP,
    notes = CONCAT(
        COALESCE(notes, ''),
        CASE WHEN COALESCE(notes, '') = '' THEN '' ELSE E'\n' END,
        'Automatisk skjult fordi forbindelsen manglede adresse efter import.'
    ),
    status = 'pending'
WHERE deleted_at IS NULL
  AND provider ILIKE 'GlobalConnect%'
  AND (address IS NULL OR BTRIM(address) = '');
