"""Tests for relay server authentication."""

import time
from p2p.identity import PeerIdentity
from p2p.relay_server import _verify_registration, _pinned_keys


class TestRelayAuth:
    def setup_method(self):
        _pinned_keys.clear()

    def test_valid_registration(self):
        i = PeerIdentity.generate()
        ts = int(time.time())
        sig = i.sign(f"REGISTER:{i.peer_id}:{ts}".encode())
        assert _verify_registration(i.peer_id, i.public_key_raw().hex(), sig.hex(), ts)

    def test_wrong_signature(self):
        i = PeerIdentity.generate()
        ts = int(time.time())
        sig = i.sign(b"wrong data")
        assert not _verify_registration(i.peer_id, i.public_key_raw().hex(), sig.hex(), ts)

    def test_peer_id_mismatch(self):
        i = PeerIdentity.generate()
        ts = int(time.time())
        sig = i.sign(f"REGISTER:p2p:fake:{ts}".encode())
        assert not _verify_registration("p2p:fake", i.public_key_raw().hex(), sig.hex(), ts)

    def test_tofu_different_key_rejected(self):
        """TOFU: second registration with different key is rejected."""
        i1 = PeerIdentity.generate()
        ts = int(time.time())
        sig1 = i1.sign(f"REGISTER:{i1.peer_id}:{ts}".encode())
        assert _verify_registration(i1.peer_id, i1.public_key_raw().hex(), sig1.hex(), ts)

        i2 = PeerIdentity.generate()
        sig2 = i2.sign(f"REGISTER:{i1.peer_id}:{ts}".encode())
        assert not _verify_registration(i1.peer_id, i2.public_key_raw().hex(), sig2.hex(), ts)

    def test_same_key_reregistration(self):
        i = PeerIdentity.generate()
        ts = int(time.time())
        sig = i.sign(f"REGISTER:{i.peer_id}:{ts}".encode())
        assert _verify_registration(i.peer_id, i.public_key_raw().hex(), sig.hex(), ts)
        sig2 = i.sign(f"REGISTER:{i.peer_id}:{ts}".encode())
        assert _verify_registration(i.peer_id, i.public_key_raw().hex(), sig2.hex(), ts)

    def test_bad_pubkey_length(self):
        assert not _verify_registration("p2p:x", "aabb", "ccdd", time.time())

    def test_stale_timestamp_rejected(self):
        """Timestamp > 60s old is rejected."""
        i = PeerIdentity.generate()
        old_ts = int(time.time()) - 120  # 2 minutes ago
        sig = i.sign(f"REGISTER:{i.peer_id}:{old_ts}".encode())
        assert not _verify_registration(i.peer_id, i.public_key_raw().hex(), sig.hex(), old_ts)

    def test_future_timestamp_rejected(self):
        """Timestamp > 60s in future is rejected."""
        i = PeerIdentity.generate()
        future_ts = int(time.time()) + 120
        sig = i.sign(f"REGISTER:{i.peer_id}:{future_ts}".encode())
        assert not _verify_registration(i.peer_id, i.public_key_raw().hex(), sig.hex(), future_ts)
