import json

from src.security import credentials


def test_credentials_are_dpapi_encrypted_and_restored(tmp_path, mocker):
    path = tmp_path / 'credentials.bin'
    mocker.patch.object(credentials, 'CREDENTIALS_PATH', path)
    protect = mocker.patch.object(
        credentials.win32crypt,
        'CryptProtectData',
        return_value=b'encrypted',
    )
    unprotect = mocker.patch.object(
        credentials.win32crypt,
        'CryptUnprotectData',
        return_value=(
            'TibiaPilotNG',
            json.dumps({'account': 'account@example.com', 'password': 'secret'}).encode(),
        ),
    )

    credentials.save_credentials(' account@example.com ', 'secret')
    assert path.read_bytes() == b'encrypted'
    assert credentials.load_credentials() == {
        'account': 'account@example.com',
        'password': 'secret',
    }
    protect.assert_called_once()
    unprotect.assert_called_once()


def test_empty_password_is_rejected(tmp_path, mocker):
    mocker.patch.object(credentials, 'CREDENTIALS_PATH', tmp_path / 'credentials.bin')

    try:
        credentials.save_credentials('account@example.com', '')
    except ValueError:
        pass
    else:
        raise AssertionError('empty password must fail')
