import pytest
import os
from kotak_dashboard.backend import AuthManager


def test_login_missing_credentials(mocker):
    """Ensure error is raised if credentials are missing."""
    # Mock os.getenv to return None
    mocker.patch.dict(os.environ, {}, clear=True)

    auth = AuthManager()
    with pytest.raises(ValueError, match="Missing Credentials"):
        auth.login()


def test_login_success(mocker):
    """Test successful login flow calling underlying client methods."""
    # Mock external libs
    mock_neo = mocker.patch("kotak_dashboard.backend.NeoAPI")
    mock_otp = mocker.patch("kotak_dashboard.backend.pyotp.TOTP")

    # Mock Environment variables
    env_vars = {
        "KOTAK_CONSUMER_KEY": "test_key",
        "KOTAK_MOBILE": "1234567890",
        "KOTAK_UCC": "UCC123",
        "KOTAK_TOTP_SECRET": "SECRET",
        "KOTAK_MPIN": "0000",
    }
    mocker.patch.dict(os.environ, env_vars, clear=True)

    auth = AuthManager()
    client = auth.login()

    # Verify NeoAPI was initialized
    mock_neo.assert_called_once()
    # Verify TOTP generation and login called
    mock_otp.return_value.now.assert_called()
    client.totp_login.assert_called_once()
    client.totp_validate.assert_called_once()
