from fastapi.testclient import TestClient

from keepedu_performance.api.app import app
from keepedu_performance.api import repository
from keepedu_performance.api import auth


client = TestClient(app)


def test_health_is_public():
    response = client.get("/health/live")

    assert response.status_code == 200
    assert response.json() == {"status": "ok"}


def test_students_reject_request_without_token():
    response = client.get("/api/v1/alunos")

    assert response.status_code == 401


def test_service_token_is_bound_to_its_tenant(monkeypatch, tmp_path):
    monkeypatch.setattr(
        auth.settings,
        "api_service_tokens",
        {
            "test-token": {
                "subject": "mobile-bff",
                "institute": "tenant-a",
                "units": ["10"],
            }
        },
    )
    monkeypatch.setattr(repository, "RUNTIME_ROOT", tmp_path)
    monkeypatch.setattr(repository.settings, "tenant_data_path", "data/tenants")
    monkeypatch.setattr(repository.settings, "keepedu_institute", "")

    response = client.get(
        "/api/v1/alunos",
        headers={"Authorization": "Bearer test-token"},
    )

    assert response.status_code == 200
    assert response.json()["items"] == []


def test_service_read_token_cannot_start_pipeline(monkeypatch):
    monkeypatch.setattr(
        auth.settings,
        "api_service_tokens",
        {"read-token": {"subject": "mobile-bff", "institute": "tenant-a"}},
    )

    response = client.post(
        "/api/v1/atualizacoes/ranking",
        headers={"Authorization": "Bearer read-token"},
        json={"unidade": "Centro", "serie": "1 Serie"},
    )

    assert response.status_code == 403


def test_openapi_exposes_extracted_business_routes():
    paths = client.get("/openapi.json").json()["paths"]

    assert "/api/v1/auth/login" in paths
    assert "/api/v1/alunos/{ra}" in paths
    assert "/api/v1/analise-notas/{visao}" in paths
    assert "/api/v1/lancamento-notas/{visao}" in paths
    assert "/api/v1/atualizacoes/ranking" in paths
    assert "/api/v1/jobs/{job_id}" in paths
