from __future__ import annotations

from urllib.parse import parse_qs, urlparse

from ebay_client.core.auth.models import EbayOAuthConfig, OAuthToken
from ebay_client.core.auth.oauth import EbayOAuthClient
from ebay_client.core.auth.store import InMemoryTokenStore


def test_build_authorization_url_uses_configured_scopes() -> None:
    config = EbayOAuthConfig(
        client_id="client-id",
        client_secret="client-secret",
        redirect_uri="https://example.test/callback",
        default_scopes=["scope.a", "scope.b"],
    )
    client = EbayOAuthClient(config)

    url = client.build_authorization_url(state="state-1")
    query = parse_qs(urlparse(url).query)

    assert query["client_id"] == ["client-id"]
    assert query["state"] == ["state-1"]
    assert query["scope"] == ["scope.a scope.b"]


def test_get_valid_token_reuses_unexpired_token() -> None:
    config = EbayOAuthConfig(client_id="client-id", client_secret="client-secret")
    store = InMemoryTokenStore()
    store.set_token(OAuthToken(access_token="cached-token", scope="scope.a"))
    client = EbayOAuthClient(config, token_store=store)

    token = client.get_valid_token(scopes=["scope.a"])

    assert token.access_token == "cached-token"


def test_get_valid_token_reuses_token_when_any_scope_option_matches() -> None:
    config = EbayOAuthConfig(client_id="client-id", client_secret="client-secret")
    store = InMemoryTokenStore()
    store.set_token(OAuthToken(access_token="cached-token", scope="scope.base scope.write"))
    client = EbayOAuthClient(config, token_store=store)

    token = client.get_valid_token(
        scope_options=[
            ["scope.base", "scope.read"],
            ["scope.base", "scope.write"],
        ]
    )

    assert token.access_token == "cached-token"
