"""Tests for PSA credential encryption/decryption."""
import pytest
from app.services.psa.encryption import encrypt_credentials, decrypt_credentials


class TestCredentialEncryption:
    def test_round_trip(self):
        """Encrypt then decrypt returns original credentials."""
        creds = {
            "public_key": "abc123",
            "private_key": "secret456",
            "client_id": "my-client-id",
        }
        encrypted = encrypt_credentials(creds)

        # Encrypted should be a non-empty string, different from input
        assert isinstance(encrypted, str)
        assert len(encrypted) > 0
        assert "secret456" not in encrypted

        decrypted = decrypt_credentials(encrypted)
        assert decrypted == creds

    def test_different_inputs_produce_different_outputs(self):
        creds1 = {"public_key": "key1", "private_key": "priv1", "client_id": "cid1"}
        creds2 = {"public_key": "key2", "private_key": "priv2", "client_id": "cid2"}

        enc1 = encrypt_credentials(creds1)
        enc2 = encrypt_credentials(creds2)
        assert enc1 != enc2

    def test_tampered_ciphertext_raises(self):
        creds = {"public_key": "k", "private_key": "p", "client_id": "c"}
        encrypted = encrypt_credentials(creds)
        tampered = encrypted[:-5] + "XXXXX"
        with pytest.raises(Exception):
            decrypt_credentials(tampered)

    def test_mask_private_key(self):
        from app.services.psa.encryption import mask_credential
        assert mask_credential("abcdefghij") == "\u2022\u2022\u2022\u2022\u2022\u2022ghij"
        assert mask_credential("abc") == "\u2022\u2022\u2022\u2022\u2022\u2022abc"
        assert mask_credential("") == "\u2022\u2022\u2022\u2022\u2022\u2022"
        assert mask_credential(None) == "\u2022\u2022\u2022\u2022\u2022\u2022"
