import pytest
from fastapi import HTTPException
from starlette.requests import Request


def _make_request() -> Request:
    """Minimal Request stub for verify_webai_key (only request.url.path + request.client used)."""
    scope = {
        "type": "http",
        "path": "/api/webai/test",
        "headers": [],
        "client": ("1.2.3.4", 12345),
    }
    return Request(scope=scope)


def test_verify_with_valid_key_passes(monkeypatch):
    monkeypatch.setenv("WEBAI_API_KEY", "secret-key-abc")
    from app.auth import verify_webai_key
    verify_webai_key(_make_request(), x_webai_key="secret-key-abc")


def test_verify_without_key_raises_401(monkeypatch):
    monkeypatch.setenv("WEBAI_API_KEY", "secret-key-abc")
    from app.auth import verify_webai_key
    with pytest.raises(HTTPException) as exc:
        verify_webai_key(_make_request(), x_webai_key=None)
    assert exc.value.status_code == 401
    assert "X-WebAI-Key" in exc.value.detail


def test_verify_with_wrong_key_raises_401(monkeypatch):
    monkeypatch.setenv("WEBAI_API_KEY", "secret-key-abc")
    from app.auth import verify_webai_key
    with pytest.raises(HTTPException) as exc:
        verify_webai_key(_make_request(), x_webai_key="wrong-key")
    assert exc.value.status_code == 401


def test_verify_returns_503_when_env_missing(monkeypatch):
    monkeypatch.delenv("WEBAI_API_KEY", raising=False)
    from app.auth import verify_webai_key
    with pytest.raises(HTTPException) as exc:
        verify_webai_key(_make_request(), x_webai_key="anything")
    assert exc.value.status_code == 503
