import os
import pytest
from cryptography.fernet import Fernet
from upstox_auth.storage import EncryptedFileStorage
from upstox_auth.exceptions import StorageError

def test_encrypted_file_storage(tmp_path):
    key = Fernet.generate_key().decode()
    file_path = tmp_path / "encrypted_token.bin"
    storage = EncryptedFileStorage(str(file_path), key)
    
    token_data = {"access_token": "secret_123", "fetched_at": "2026-01-01T00:00:00"}
    storage.save_token(token_data)
    
    assert os.path.exists(file_path)
    
    # Verify file is not plain text
    with open(file_path, "rb") as f:
        content = f.read()
        assert b"secret_123" not in content
        
    # Verify decryption
    loaded_data = storage.get_token()
    assert loaded_data["access_token"] == "secret_123"

def test_encrypted_file_storage_wrong_key(tmp_path):
    key1 = Fernet.generate_key().decode()
    key2 = Fernet.generate_key().decode()
    file_path = tmp_path / "encrypted_token.bin"
    
    storage1 = EncryptedFileStorage(str(file_path), key1)
    token_data = {"token": "data"}
    storage1.save_token(token_data)
    
    storage2 = EncryptedFileStorage(str(file_path), key2)
    with pytest.raises(StorageError):
        storage2.get_token()
