"""Unit tests for navi.auth.encrypt."""

import pytest

from navi.auth.encrypt import TokenEncryptor, get_encryptor


class TestTokenEncryptor:
    # Fernet key must be 32 url-safe base64-encoded bytes
    _KEY = "hocAswNbSlUFITrAPnpv-3ky9EpiZBqZs0km73FR5nE="

    def test_encrypt_decrypt_roundtrip(self):
        enc = TokenEncryptor(self._KEY)
        plain = "sensitive-token-data"
        cipher = enc.encrypt(plain)
        assert cipher != plain
        assert enc.decrypt(cipher) == plain

    def test_different_plaintexts_produce_different_ciphers(self):
        enc = TokenEncryptor(self._KEY)
        c1 = enc.encrypt("data1")
        c2 = enc.encrypt("data2")
        assert c1 != c2

    def test_empty_key_raises(self):
        with pytest.raises(ValueError, match="required"):
            TokenEncryptor("")

    def test_short_key_raises(self):
        with pytest.raises(ValueError):
            TokenEncryptor("short")

    def test_invalid_base64_key_raises(self):
        with pytest.raises(ValueError):
            TokenEncryptor("not-a-valid-base64-key!!!")


class TestGetEncryptor:
    def test_singleton_returns_same_instance(self):
        # Reset singleton for test isolation
        import navi.auth.encrypt as _mod

        _mod._encryptor = TokenEncryptor(
            "hocAswNbSlUFITrAPnpv-3ky9EpiZBqZs0km73FR5nE="
        )
        e1 = get_encryptor()
        e2 = get_encryptor()
        assert e1 is e2
