"""Tests for the Fernet crypto service."""
from __future__ import annotations

import pytest
from cryptography.fernet import Fernet

from backend.app.services.crypto import C2Disabled, decrypt, encrypt


@pytest.fixture()
def fernet_key(monkeypatch) -> str:
    key = Fernet.generate_key().decode()
    monkeypatch.setenv("MIMIC_ENCRYPTION_KEY", key)
    return key


@pytest.fixture()
def no_key(monkeypatch):
    monkeypatch.delenv("MIMIC_ENCRYPTION_KEY", raising=False)


class TestEncryptDecrypt:
    def test_round_trip(self, fernet_key):
        plaintext = "s3cr3t-api-token"
        ciphertext = encrypt(plaintext)
        assert ciphertext != plaintext
        assert decrypt(ciphertext) == plaintext

    def test_different_tokens_for_same_input(self, fernet_key):
        # Fernet tokens are non-deterministic (random IV).
        t1 = encrypt("same")
        t2 = encrypt("same")
        assert t1 != t2
        assert decrypt(t1) == decrypt(t2) == "same"

    def test_decrypt_invalid_ciphertext(self, fernet_key):
        with pytest.raises(ValueError):
            decrypt("not-valid-fernet-token")


class TestKeyAbsent:
    def test_encrypt_raises_c2disabled(self, no_key):
        with pytest.raises(C2Disabled):
            encrypt("anything")

    def test_decrypt_raises_c2disabled(self, no_key):
        with pytest.raises(C2Disabled):
            decrypt("anything")

    def test_c2disabled_message(self, no_key):
        with pytest.raises(C2Disabled, match="MIMIC_ENCRYPTION_KEY"):
            encrypt("x")
