from unittest.mock import MagicMock, patch

import pytest
from fastapi import HTTPException, Request

from app.core.config import settings
from app.core.redis import check_rate_limit, client_ip, _buckets


def test_check_rate_limit_uses_memory_fallback(monkeypatch):
    monkeypatch.setattr(settings, "enable_rate_limit", True)
    _buckets.clear()
    with patch("app.core.redis.get_redis_client", return_value=None):
        check_rate_limit("memory-key", limit=1, window_seconds=60)
        with pytest.raises(HTTPException) as exc:
            check_rate_limit("memory-key", limit=1, window_seconds=60)
        assert exc.value.status_code == 429


def test_client_ip_honors_trusted_proxy(monkeypatch):
    monkeypatch.setattr(settings, "trusted_proxy_ips", "127.0.0.1")
    request = MagicMock(spec=Request)
    request.headers = {"X-Forwarded-For": "203.0.113.10, 127.0.0.1"}
    request.client.host = "127.0.0.1"
    assert client_ip(request) == "203.0.113.10"


def test_client_ip_unknown_without_client():
    request = MagicMock(spec=Request)
    request.headers = {}
    request.client = None
    assert client_ip(request) == "unknown"
