from pathlib import Path
import pytest


def test_nik_requires_exactly_16_ascii_digits():
    from app.core.customer_identity import validate_nik

    assert validate_nik("8271010101010001") == "8271010101010001"
    for invalid in ("", "827101010101001", "82710101010100011", "8271-0101-0101-0001", "１２３４５６７８９０１２３４５６"):
        with pytest.raises(ValueError):
            validate_nik(invalid)


def test_customer_code_and_default_pppoe_username_are_permanent_and_deterministic():
    from app.core.customer_identity import customer_code_for, default_pppoe_username

    code = customer_code_for(42)
    assert code == "PLG-0000042"
    assert default_pppoe_username(code) == code


def test_customer_identity_ui_does_not_render_password_in_general_views():
    root = Path(__file__).parents[1] / "app" / "templates"
    for name in ("customers.html", "customer_detail.html"):
        assert "pppoe_password" not in (root / name).read_text(encoding="utf-8")
    add_form = (root / "add_customer.html").read_text(encoding="utf-8")
    assert 'name="nik"' in add_form
    assert 'pattern="[0-9]{16}"' in add_form
    credential_page = (root / "credential_notice.html").read_text(encoding="utf-8")
    assert "Jangan screenshot" in credential_page


def test_password_secret_round_trip_is_not_stored_as_plaintext(monkeypatch):
    from cryptography.fernet import Fernet
    monkeypatch.setenv("BESTWEB_SECRET_KEY", Fernet.generate_key().decode())
    from app.core.customer_identity import encrypt_default_pppoe_password, decrypt_pppoe_password

    encrypted = encrypt_default_pppoe_password("PLG-0000042")
    assert encrypted != "PLG-0000042"
    assert decrypt_pppoe_password(encrypted) == "PLG-0000042"
