"""Test OAuth credential storage."""
import pytest
import tempfile
from pathlib import Path
from nanobot.config.oauth_store import OAuthStore
from nanobot.config.schema import OAuthCredentials


@pytest.fixture
def temp_store():
    """Create store with temp directory."""
    with tempfile.TemporaryDirectory() as tmpdir:
        yield OAuthStore(Path(tmpdir) / ".nanobot")


def test_save_and_load_credentials(temp_store):
    """Should save and load OAuth credentials."""
    creds = OAuthCredentials(
        access_token="sk-ant-oat01-xxx",
        refresh_token="rt_xxx",
        expires_at=1234567890
    )

    temp_store.save("anthropic", creds)
    loaded = temp_store.load("anthropic")

    assert loaded is not None
    assert loaded.access_token == creds.access_token
    assert loaded.refresh_token == creds.refresh_token


def test_load_nonexistent_returns_none(temp_store):
    """Should return None for missing credentials."""
    assert temp_store.load("nonexistent") is None


def test_delete_credentials(temp_store):
    """Should delete saved credentials."""
    creds = OAuthCredentials(access_token="sk-ant-oat01-xxx")
    temp_store.save("anthropic", creds)
    assert temp_store.delete("anthropic") is True
    assert temp_store.load("anthropic") is None


def test_delete_nonexistent_returns_false(temp_store):
    """Should return False when deleting missing credentials."""
    assert temp_store.delete("nonexistent") is False


def test_file_permissions(temp_store):
    """Credentials file should have restricted permissions."""
    creds = OAuthCredentials(access_token="sk-ant-oat01-xxx")
    temp_store.save("anthropic", creds)
    perms = oct(temp_store.file_path.stat().st_mode)[-3:]
    assert perms == "600"
