import pytest
from fastapi.testclient import TestClient

from sitedrop.server.app import create_app
from sitedrop.server.auth import hash_password
from sitedrop.server.config import ServerConfig
from sitedrop.server.routes_api import _auth_attempts


@pytest.fixture(autouse=True)
def _clear_rate_limit():
    """Reset rate limiter state between tests."""
    _auth_attempts.clear()
    yield
    _auth_attempts.clear()


@pytest.fixture
def tmp_sites_dir(tmp_path):
    sites = tmp_path / "sites"
    sites.mkdir()
    return sites


@pytest.fixture
def server_config(tmp_sites_dir, tmp_path):
    return ServerConfig(
        password_hash=hash_password("testpass"),
        jwt_secret="test-secret-key-that-is-long-enough-for-hs256-jwt",
        sites_dir=str(tmp_sites_dir),
    )


@pytest.fixture
def app(server_config):
    return create_app(server_config)


@pytest.fixture
def client(app):
    return TestClient(app)


@pytest.fixture
def auth_headers(client):
    resp = client.post("/api/auth", json={"password": "testpass"})
    token = resp.json()["token"]
    return {"Authorization": f"Bearer {token}"}
