"""{{ display_name }} MCP server — generated by mcpify. Do not hand-edit."""

from __future__ import annotations

import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from {{ module_name }}.auth.errors import MissingCredentialsError
from {{ module_name }}.auth.strategies.oauth1 import (
    OAuth1Strategy,
    _oauth_encode,
    build_authorization_header,
)


def _test_key_pem() -> str:
    key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    return key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    ).decode()


def test_oauth_encode_leaves_unreserved_characters_untouched() -> None:
    assert _oauth_encode("abc123-._~") == "abc123-._~"
    assert _oauth_encode("a b") == "a%20b"
    assert _oauth_encode("a/b") == "a%2Fb"


def test_builds_a_well_formed_oauth_authorization_header() -> None:
    header = build_authorization_header(
        "consumer-key",
        _test_key_pem(),
        "token-value",
        "GET",
        "https://api.example.com/widgets?foo=bar",
    )

    assert header.startswith("OAuth ")
    assert 'oauth_consumer_key="consumer-key"' in header
    assert 'oauth_signature_method="RSA-SHA1"' in header
    assert 'oauth_token="token-value"' in header
    assert "oauth_signature=" in header


def test_rejects_a_malformed_private_key() -> None:
    with pytest.raises(Exception):
        build_authorization_header(
            "consumer-key", "not a real key", None, "GET", "https://api.example.com/widgets"
        )


async def test_authenticate_requires_consumer_key_and_private_key() -> None:
    strategy = OAuth1Strategy()
    with pytest.raises(MissingCredentialsError):
        await strategy.authenticate({})
