"""Password hashing and rules (no database)."""
import pytest

from app.core import passwords
from app.core.config import settings


def test_hash_verifies_and_is_salted():
    a, b = passwords.hash_password("correct horse"), passwords.hash_password("correct horse")
    assert a != b  # a new salt every time
    assert passwords.verify_password("correct horse", a) and passwords.verify_password("correct horse", b)
    assert not passwords.verify_password("wrong", a)
    assert "correct horse" not in a


def test_hash_format_carries_its_cost():
    algorithm, iterations, salt, digest = passwords.hash_password("x", iterations=1234).split("$")
    assert algorithm == "pbkdf2_sha256" and iterations == "1234"
    assert len(bytes.fromhex(salt)) == 16 and len(bytes.fromhex(digest)) == 32


def test_an_old_hash_still_verifies_after_the_cost_is_raised(monkeypatch):
    old = passwords.hash_password("pw12345678", iterations=500)
    monkeypatch.setattr(settings, "password_hash_iterations", 5000)
    assert passwords.verify_password("pw12345678", old)
    assert passwords.hash_password("pw12345678").split("$")[1] == "5000"


@pytest.mark.parametrize("stored", ["", "plain", "a$b$c", "md5$1$00$00", "pbkdf2_sha256$x$00$00",
                                    "pbkdf2_sha256$10$zz$00", None])
def test_garbage_never_verifies_and_never_raises(stored):
    assert passwords.verify_password("anything", stored) is False


@pytest.mark.parametrize("new,current,fragment", [
    ("short", None, "at least 8"),
    ("x" * 129, None, "at most 128"),
    ("123456", None, "at least 8"),  # too short anyway
    ("pw12345678", "pw12345678", "differ"),
    (" spaced-pw1 ", None, "spaces"),
])
def test_password_rules(new, current, fragment):
    assert fragment in passwords.password_problem(new, current)


def test_the_default_password_cannot_be_chosen(monkeypatch):
    monkeypatch.setattr(settings, "default_password", "Welcome-2026")
    assert "default" in passwords.password_problem("Welcome-2026")
    assert passwords.password_problem("a-fine-passphrase") is None


def test_the_shipped_default_is_123456():
    assert settings.default_password == "123456"


async def test_async_helpers_agree_with_the_sync_ones():
    stored = await passwords.hash_password_async("pw12345678")
    assert await passwords.verify_password_async("pw12345678", stored)
    assert not await passwords.verify_password_async("nope", stored)
