"""Tests for the Auth resource API."""

from pathlib import Path

import httpx
import pytest

from mld_sdk.client._config import get_default_host, get_stored_token
from mld_sdk.client._http import HTTPClient
from mld_sdk.client.resources.auth import AuthAPI


@pytest.fixture(autouse=True)
def _isolated_config(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))


def _make_auth_api(handler) -> AuthAPI:
    http = HTTPClient("http://localhost:8001")
    http._client = httpx.Client(
        base_url="http://localhost:8001",
        transport=httpx.MockTransport(handler),
    )
    return AuthAPI(http)


class TestAuthLogin:
    def test_login_stores_token_and_sets_default_host(self):
        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(
                200,
                json={
                    "access_token": "jwt-123",
                    "token_type": "bearer",
                    "expires_in": 3600,
                    "user": {"id": "1", "username": "admin", "role": "admin"},
                },
            )

        api = _make_auth_api(handler)
        result = api.login("admin", "password")

        assert result["access_token"] == "jwt-123"
        assert result["user"]["username"] == "admin"

        # Token stored in config
        assert get_stored_token("http://localhost:8001") == "jwt-123"
        assert get_default_host() == "http://localhost:8001"

    def test_login_sets_http_client_token(self):
        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(
                200,
                json={
                    "access_token": "new-jwt",
                    "expires_in": 3600,
                    "user": {"id": "1", "username": "user1", "role": "user"},
                },
            )

        api = _make_auth_api(handler)
        api.login("user1", "pass")
        assert api._http._token == "new-jwt"


class TestAuthLogout:
    def test_logout_clears_stored_token(self):
        call_log: list[str] = []

        def handler(request: httpx.Request) -> httpx.Response:
            if "/login" in str(request.url):
                return httpx.Response(
                    200,
                    json={
                        "access_token": "tok",
                        "expires_in": 3600,
                        "user": {"id": "1", "username": "admin", "role": "admin"},
                    },
                )
            call_log.append("logout")
            return httpx.Response(200, json={"status": "ok"})

        api = _make_auth_api(handler)
        api.login("admin", "pass")
        assert get_stored_token("http://localhost:8001") == "tok"

        api.logout()
        assert get_stored_token("http://localhost:8001") is None
        assert api._http._token is None

    def test_logout_clears_even_if_server_fails(self):
        from mld_sdk.client._config import store_token

        store_token("http://localhost:8001", "tok", "admin")

        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(500, json={"detail": "down"})

        api = _make_auth_api(handler)
        api.logout()  # Should not raise
        assert get_stored_token("http://localhost:8001") is None


class TestAuthVerify:
    def test_verify_returns_user_info(self):
        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(
                200,
                json={
                    "valid": True,
                    "username": "admin",
                    "user": {"id": "1", "username": "admin", "role": "admin"},
                    "expires_at": "2026-04-01T00:00:00Z",
                },
            )

        api = _make_auth_api(handler)
        result = api.verify()
        assert result["valid"] is True
        assert result["user"]["role"] == "admin"

    def test_whoami_is_alias_for_verify(self):
        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(
                200,
                json={
                    "valid": True,
                    "username": "user1",
                    "user": {"id": "2", "username": "user1", "role": "user"},
                },
            )

        api = _make_auth_api(handler)
        assert api.whoami() == api.verify()


class TestAuthRefresh:
    def test_refresh_updates_token(self):
        def handler(request: httpx.Request) -> httpx.Response:
            return httpx.Response(
                200,
                json={
                    "access_token": "refreshed-jwt",
                    "token_type": "bearer",
                    "expires_in": 3600,
                },
            )

        api = _make_auth_api(handler)
        result = api.refresh()
        assert result["access_token"] == "refreshed-jwt"
        assert api._http._token == "refreshed-jwt"
