"""Tests for upstream token management."""

from __future__ import annotations

import os

import pytest

from radix_edge.upstream.token_manager import persist_token, load_token, resolve_token


class TestTokenPersistence:
    def test_persist_and_load(self, tmp_path):
        token_file = str(tmp_path / "cluster_token")
        persist_token("secret-token-123", token_file)
        loaded = load_token(token_file)
        assert loaded == "secret-token-123"

    def test_load_nonexistent(self, tmp_path):
        result = load_token(str(tmp_path / "nonexistent"))
        assert result is None

    def test_load_empty_file(self, tmp_path):
        token_file = tmp_path / "empty_token"
        token_file.write_text("")
        result = load_token(str(token_file))
        assert result is None

    def test_file_permissions(self, tmp_path):
        token_file = str(tmp_path / "cluster_token")
        persist_token("secret", token_file)
        mode = os.stat(token_file).st_mode & 0o777
        assert mode == 0o600

    def test_creates_parent_dirs(self, tmp_path):
        token_file = str(tmp_path / "nested" / "dir" / "token")
        persist_token("token-val", token_file)
        assert load_token(token_file) == "token-val"


class TestResolveToken:
    @pytest.mark.asyncio
    async def test_env_token_takes_priority(self, tmp_path):
        token_file = str(tmp_path / "token")
        persist_token("file-token", token_file)

        result = await resolve_token(
            api_base="https://api.test.com",
            cluster_id="c1",
            tenant_id="t1",
            cluster_token="env-token",
            one_time_token="",
            token_file=token_file,
        )
        assert result == "env-token"

    @pytest.mark.asyncio
    async def test_file_token_second_priority(self, tmp_path):
        token_file = str(tmp_path / "token")
        persist_token("file-token", token_file)

        result = await resolve_token(
            api_base="https://api.test.com",
            cluster_id="c1",
            tenant_id="t1",
            cluster_token="",
            one_time_token="",
            token_file=token_file,
        )
        assert result == "file-token"

    @pytest.mark.asyncio
    async def test_no_token_raises(self, tmp_path):
        with pytest.raises(RuntimeError, match="No cluster token available"):
            await resolve_token(
                api_base="https://api.test.com",
                cluster_id="c1",
                tenant_id="t1",
                cluster_token="",
                one_time_token="",
                token_file=str(tmp_path / "nonexistent"),
            )

    @pytest.mark.asyncio
    async def test_one_time_exchange(self, tmp_path, respx_mock):
        token_file = str(tmp_path / "token")
        respx_mock.post("https://api.test.com/v1/clusters/c1/auth/exchange").respond(
            json={"cluster_token": "exchanged-token"}
        )

        result = await resolve_token(
            api_base="https://api.test.com",
            cluster_id="c1",
            tenant_id="t1",
            cluster_token="",
            one_time_token="one-time-secret",
            token_file=token_file,
        )
        assert result == "exchanged-token"
        # Should also be persisted
        assert load_token(token_file) == "exchanged-token"
