import os

from auth import create_access_token, verify_access_token
from database import hash_password, password_needs_rehash, verify_password


def test_pbkdf2_password_hash_is_salted_and_verifiable():
    first = hash_password("Strong-Test-Password")
    second = hash_password("Strong-Test-Password")
    assert first != second
    assert verify_password("Strong-Test-Password", first)
    assert not verify_password("wrong", first)
    assert not password_needs_rehash(first)


def test_legacy_sha256_password_can_be_migrated():
    import hashlib

    legacy = hashlib.sha256(b"legacy-password").hexdigest()
    assert verify_password("legacy-password", legacy)
    assert password_needs_rehash(legacy)


def test_access_token_rejects_tampering(monkeypatch):
    monkeypatch.setenv("SECRET_KEY", "test-secret-key-that-is-long-enough-for-tests")
    token = create_access_token(1, "admin", "admin")
    assert verify_access_token(token)["sub"] == 1
    try:
        verify_access_token(token + "x")
    except ValueError:
        pass
    else:
        raise AssertionError("tampered token was accepted")
