WITH ranked AS (
    SELECT
        id,
        ip_address,
        ROW_NUMBER() OVER (
            PARTITION BY ip_address
            ORDER BY
                CASE WHEN deleted_at IS NULL THEN 0 ELSE 1 END,
                id
        ) AS row_no
    FROM internet_connections_ip_addresses
),
duplicates AS (
    SELECT id
    FROM ranked
    WHERE row_no > 1
)
UPDATE internet_connections_ip_addresses ipa
SET deleted_at = CURRENT_TIMESTAMP,
    updated_at = CURRENT_TIMESTAMP,
    comment = CONCAT(
        COALESCE(ipa.comment, ''),
        CASE WHEN COALESCE(ipa.comment, '') = '' THEN '' ELSE E'\n' END,
        'Automatisk deaktiveret som dublet-IP før unikregel.'
    )
WHERE ipa.id IN (SELECT id FROM duplicates)
  AND ipa.deleted_at IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS uq_internet_connections_ip_addresses_ip_address_active
ON internet_connections_ip_addresses (ip_address)
WHERE deleted_at IS NULL;
