<?php

declare(strict_types=1);

namespace WPStack\Sandbox\Security;

final class VisitorIdentifier
{
    public function __construct(private readonly string $secret)
    {
        if ($secret === '') {
            throw new \InvalidArgumentException('Visitor secret cannot be empty.');
        }
    }

    public function fromAddress(string $address): string
    {
        $normalized = filter_var($address, FILTER_VALIDATE_IP) ? $address : 'anonymous';

        return hash_hmac('sha256', $normalized, $this->secret);
    }

    public function fromTokenAndAddress(string $token, string $address): string
    {
        if (!preg_match('/^[a-f0-9]{32,128}$/', $token)) {
            $token = hash('sha256', $token);
        }
        $normalized = filter_var($address, FILTER_VALIDATE_IP) ? $address : 'anonymous';

        return hash_hmac('sha256', $token . '|' . $normalized, $this->secret);
    }
}
