import pytest
from core.security import (
    hash_password,
    verify_password,
    create_access_token,
    create_refresh_token,
    decode_token,
    hash_token,
)
from core.encryption import encrypt_string, decrypt_string
from core.exceptions import UnauthorizedError, CryptoError


def test_password_hashing():
    pw = "SuperSecretPassword123!"
    hashed = hash_password(pw)
    assert hashed != pw
    assert hashed.startswith("$argon2id$")
    assert verify_password(pw, hashed) is True
    assert verify_password("WrongPassword!", hashed) is False


def test_aes_256_gcm_encryption():
    bot_token = "123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ"
    ciphertext, key_version = encrypt_string(bot_token)
    assert ciphertext != bot_token
    assert key_version == 1

    decrypted = decrypt_string(ciphertext, key_version)
    assert decrypted == bot_token


def test_jwt_tokens():
    payload = {"sub": "user-uuid-1234", "email": "test@example.com"}
    access_token = create_access_token(payload)
    decoded = decode_token(access_token, expected_type="access")
    assert decoded["sub"] == "user-uuid-1234"
    assert decoded["email"] == "test@example.com"
    assert decoded["type"] == "access"

    refresh_token = create_refresh_token(payload)
    decoded_refresh = decode_token(refresh_token, expected_type="refresh")
    assert decoded_refresh["sub"] == "user-uuid-1234"
    assert decoded_refresh["type"] == "refresh"

    # Verifying wrong token type raises UnauthorizedError
    with pytest.raises(UnauthorizedError):
        decode_token(access_token, expected_type="refresh")


def test_token_hashing():
    token = "some_random_session_token_value"
    hashed = hash_token(token)
    assert len(hashed) == 64
    assert hashed == hash_token(token)
