"""Tests for WhatsApp token encryption helpers."""

from unittest.mock import patch

import pytest
from cryptography.fernet import Fernet, InvalidToken

from app.services.encryption import decrypt_token, encrypt_token

TEST_KEY = Fernet.generate_key().decode()
ALT_TEST_KEY = Fernet.generate_key().decode()


class TestWhatsAppEncryption:
    def test_encrypt_decrypt_roundtrip(self):
        plaintext = "wa-access-token"

        encrypted = encrypt_token(plaintext, key=TEST_KEY)

        assert decrypt_token(encrypted, key=TEST_KEY) == plaintext

    def test_encrypt_returns_bytes(self):
        encrypted = encrypt_token("wa-access-token", key=TEST_KEY)

        assert isinstance(encrypted, bytes)

    def test_decrypt_wrong_key_raises(self):
        encrypted = encrypt_token("wa-access-token", key=TEST_KEY)

        with pytest.raises(InvalidToken):
            decrypt_token(encrypted, key=ALT_TEST_KEY)

    def test_encrypt_with_explicit_key(self):
        plaintext = "wa-access-token"
        explicit_key = Fernet.generate_key().decode()

        encrypted = encrypt_token(plaintext, key=explicit_key)

        assert decrypt_token(encrypted, key=explicit_key) == plaintext

    def test_missing_env_key_raises(self, monkeypatch: pytest.MonkeyPatch):
        monkeypatch.delenv("WHATSAPP_TOKEN_ENCRYPTION_KEY", raising=False)
        encrypted = encrypt_token("wa-access-token", key=TEST_KEY)

        with pytest.raises(RuntimeError, match="WHATSAPP_TOKEN_ENCRYPTION_KEY is not set"):
            encrypt_token("wa-access-token")

        with pytest.raises(RuntimeError, match="WHATSAPP_TOKEN_ENCRYPTION_KEY is not set"):
            decrypt_token(encrypted)

    def test_key_version_rotation_concept(self):
        plaintext = "wa-access-token"

        with patch.dict(
            "os.environ",
            {"WHATSAPP_TOKEN_ENCRYPTION_KEY": TEST_KEY},
            clear=False,
        ):
            encrypted = encrypt_token(plaintext)
            assert decrypt_token(encrypted) == plaintext

        with (
            patch.dict(
                "os.environ",
                {"WHATSAPP_TOKEN_ENCRYPTION_KEY": ALT_TEST_KEY},
                clear=False,
            ),
            pytest.raises(InvalidToken),
        ):
            decrypt_token(encrypted)
