import json
import os

import pytest

from upstox_auth import FileStorage, MemoryStorage


def test_memory_storage():
    storage = MemoryStorage()
    assert storage.get_token() is None

    token_data = {"access_token": "abc"}
    storage.save_token(token_data)
    assert storage.get_token() == token_data


def test_file_storage(tmp_path):
    file_path = tmp_path / "test_token.json"
    storage = FileStorage(str(file_path))

    assert storage.get_token() is None

    token_data = {"access_token": "xyz"}
    storage.save_token(token_data)

    assert os.path.exists(file_path)
    assert storage.get_token() == token_data

    # Verify file content
    with open(file_path, "r") as f:
        data = json.load(f)
        assert data == token_data


def test_file_storage_creates_directory(tmp_path):
    sub_dir = tmp_path / "subdir"
    file_path = sub_dir / "token.json"
    storage = FileStorage(str(file_path))

    token_data = {"token": "nested"}
    storage.save_token(token_data)

    assert os.path.exists(file_path)
    assert storage.get_token() == token_data


def test_file_storage_invalid_json(tmp_path):
    file_path = tmp_path / "bad_token.json"
    with open(file_path, "w") as f:
        f.write("not json")

    storage = FileStorage(str(file_path))
    from upstox_auth.exceptions import StorageError
    with pytest.raises(StorageError):
        storage.get_token()
