from app.core.config import settings


def test_oversized_declared_body_is_rejected(client, monkeypatch):
    monkeypatch.setattr(settings, "max_request_body_bytes", 10)
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": "0912345678", "name": "A Name Longer Than Ten Bytes"},
    )
    assert resp.status_code == 413


def test_body_within_limit_is_accepted(client, monkeypatch):
    monkeypatch.setattr(settings, "max_request_body_bytes", 10_000)
    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": "0912345678", "name": "Someone"},
    )
    assert resp.status_code == 200, resp.text


def _phone(i: int) -> str:
    return f"09{i:08d}"


def test_global_rate_limit_trips_across_endpoints(client, monkeypatch):
    monkeypatch.setattr(settings, "global_rate_limit_max_requests", 2)
    monkeypatch.setattr(settings, "global_rate_limit_window_seconds", 60)

    for i in range(2):
        resp = client.post(
            "/api/v1/auth/signup/start",
            json={"phone": _phone(i), "name": "Test"},
        )
        assert resp.status_code == 200, resp.text

    resp = client.post(
        "/api/v1/auth/signup/start",
        json={"phone": _phone(99), "name": "Test"},
    )
    assert resp.status_code == 429


def test_global_rate_limit_exempts_health_checks(client, monkeypatch):
    monkeypatch.setattr(settings, "global_rate_limit_max_requests", 1)
    monkeypatch.setattr(settings, "global_rate_limit_window_seconds", 60)

    for _ in range(5):
        resp = client.get("/api/v1/health")
        assert resp.status_code == 200
