<?php

declare(strict_types=1);

namespace CpCreation\AltchaBundle\Security;

final class ClientIdentity
{
    public function normalizeIp(?string $clientIp): string
    {
        if (null === $clientIp) {
            return 'unknown';
        }

        $packed = @inet_pton(trim($clientIp));
        if (false === $packed) {
            return 'unknown';
        }

        if (16 === strlen($packed) && str_starts_with($packed, str_repeat("\0", 10)."\xff\xff")) {
            $packed = substr($packed, 12, 4);
        } elseif (16 === strlen($packed)) {
            $packed = substr($packed, 0, 8).str_repeat("\0", 8);
        }

        return inet_ntop($packed) ?: 'unknown';
    }
}
